我有两个不同的IEnumerables:
CCD_ 1&IEnumerable<TypeB> ListB
这两种类型都具有称为";PersString";。
我的目标是为列表A中的每个项目获得列表B中具有相同";PersString";。
我从ListA中的ForEach循环开始,嵌套ListB的ForEah循环;PersString";ListA项目的";PersString";ListB项的。
有没有一种使用Linq进行编码的更有效的方法?
谢谢。
是否有使用Linq进行更有效编码的方法?
是的,您可以加入他们。在Linq To Object中,这(更(有效:
var query = from a in ListA
join b in ListB on a.PersString equals b.PersString
select (A: a, B: b);
除了Enumerable.Join
,LINQ还提供了Enumerable.Intersect
方法,并且自.NET6以来,提供了更方便、更强大的Enumerable.IntersectBy
。
在Enumerable.Intersect
的情况下,更复杂的类型需要您提供IEqualityComparer<T>
实现,或者让数据类型本身实现IEquatable<T>
来定义该类型的相等性。
示例Intersect
(.NET 6之前的版本(:
不支持比较不同类型的两个集合。
class Person : IEquatable<Person>
{
public bool Equals(Person p) => this.PersString == p?.PersString;
public override int GetHashCode() => HashCode.Combine(PersString);
public int ID { get; set; }
public string PersString { get; set; }
}
IEnumerable<Person> collectionA;
IEnumerable<Person> collectionB;
IEnumerable<Person> equalPersonInstances = collectionA.Intersect(collectionB);
// In case the compared type does not implement IEquatable, we would have to provide an IEqualityComparer
// IEnumerable<Person> equalMyTypeInstances = collectionA.Intersect(collectionB, new MyComparer());
示例IEnumerable<TypeA> ListA
0(.NET 6及更高版本(:
由于.NET6,我们可以使用...By
方法作为相等比较器传入lambda表达式或方法组。在这种情况下,我们调用Enumeable.IntersectBy
,它支持查找两个不同类型集合的交集。
IEnumerable<PersonA> collectionA;
IEnumerable<PersonB> collectionB;
IEnumerable<PersonA> intersection = collectionA.IntersectBy(
collectionB.Select(personB => personB.PersString),
personA => personA.PersString);
示例Join
(使用LINQEnumerable
扩展方法(
对于那些喜欢使用LINQ扩展方法的人:
IEnumerable<PersonA> collectionA;
IEnumerable<PersonB> collectionB;
// The result is a set of ValueTuple
IEnumerable<(Person, PersonB)> intersection = collectionA.Join(
collectionB,
personA => personA.PersString,
personB => personB.PersString,
(personA, personB) => (personA, personB));
Join是更有效的方式
var result = from x in ListA
join y in ListB
on x.PersString equals y.PersString
select new {x,y};