使用特定 ID 从多个 List<T> 列表中获取对象

3
在C#中,如果我有多个List列表,其中列表中的每个项都继承了一个具有id属性的接口,那么检索具有特定id的对象的最佳方法是什么?
所有ids都是唯一的,所有列表都存储在一个对象中。
我目前正在考虑为每个列表编写一个Find代码,并且如果返回的对象不为空,则返回的对象即为具有该id的对象。
是否有更好的方法来做到这一点?
请注意,这个问题是关于如何在多个列表中找到一个对象,而不是在单个列表中查找对象的代码。

1
你能否将List<T>转换为Dictionary<TKey,TValue>,其中TKey是id字段的类型,而TValue是T的类型?这样你就可以通过id查找对象了。 - nimeshjm
1
这个问题已经被问过和回答了很多次。https://dev59.com/y2445IYBdhLWcg3wTIZf 或者 https://dev59.com/K2Ij5IYBdhLWcg3wuHTP - SpaceSteak
4个回答

3

使用Linq如何:

var result = list.First(x => x.id == findThisId);

1
var result =
 new [] { list1, list2, list3, ... }
 .Select(list => list.FirstOrDefault(x => x.id == findThisId))
 .First(x => x != null);

你也可以把多个列表看作一个连接起来的列表:
var result =
 new [] { list1, list2, list3, ... }
 .SelectMany(x => x) //flatten
 .FirstOrDefault(x => x.id == findThisId);

0
var result = list.Where(i => i.Id == id).FirstOrDefault();

0

您可以创建一个列表的列表,并使用LINQ的SelectMany进行搜索:

以下是一个示例设置:

interface IId {
    int Id {get;}
}
class A : IId {
    public int Id {get;set;}
    public override string ToString() {
        return "A"+Id;
    }
}
class B : IId {
    public int Id {get;set;}
    public override string ToString() {
        return "B"+Id;
    }
}

IId 是由 AB 实现的常见接口。现在你可以这样做:

var a = new List<A> {new A {Id=5}, new A {Id=6}};
var b = new List<B> {new B {Id=7}, new B {Id=8}};
var all = new List<IEnumerable<IId>> {a, b};

all 是一个包含不同子类型的 IId 列表。由于泛型的协变规则,它需要声明为 IEnumerable 的列表。

现在你可以通过 Id 搜索 all,像这样:

var item5 = all.SelectMany(list => list).FirstOrDefault(item => item.Id == 5);

演示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接