我有一个包含多个类的列表,其中包含一个Integer(Id)属性。
我也有一个整数列表。
现在,我想将我的对象的List修剪为只有在整数列表中具有Property的那些类。
示例:
List of MyObject
[MyObjectA].Id = 1
[MyObjectB].Id = 2
[MyObjectC].Id = 3
[MyObjectD].Id = 4
List of Integer
1
2
Final list should be
[MyObjectA]
[MyObjectB]
我该怎么办?
答案 0 :(得分:7)
您可以使用contains:
var finalList = originalList.Where(x => idList.Contains(x.Id)).ToList();
或加入:
var finalList = (from entry in originalList
join id in idList on entry.Id equals id
select entry).ToList();
答案 1 :(得分:0)
这应该这样做:
// Assume objList is IEnumerable<MyObject> and intList is IEnumerable<int>.
IEnumerable<MyObject> intersection =
from obj in objList
join i in intList on obj.Id equals i
select obj
请注意,如果多个对象具有相同的ID,或者在列表中多次列出id并且一个对象对应于该对象,则该对象将在结果列表中多次显示。
我认为该组对于较大的列表更好,因为其他一些解决方案将多次遍历列表以搜索相应的对象。
答案 2 :(得分:0)
或者,如果您有两个列表,每个列表都有属性,请尝试:
List<someObj1> firstList ... //assume this has items
List<otherObj2> secondList ... //assume this has items
var finalList = firstList.Where(so1 => secondList.Select(oo2 => oo2.Prop1).Contains(so1.Prop1) && so1.Prop2 == "foo");
//Prop1 is a property of the someObj1 and otherObj objects.
//Prop2 is a property of the someObj1 object.
答案 3 :(得分:-1)
怎么样:
list.RemoveAll(x => list2.IndexOf(x.Id) >= 0);