簡體   English   中英

C#LINQ比較列表值

[英]C# LINQ comparing list values

我有兩個不同自定義類型的列表。 兩種類型共享2個共同屬性。

例如:

List<foo>;
List<bar>;

它們都具有屬性,例如名為Name和Age。

我想返回一個包含所有bar對象的新List,其中bar的Name和Age屬性出現在任何foo對象中。 最好的方法是什么?

謝謝

假設共享屬性正確實現了相等,您可能希望執行以下操作:

// In an extensions class somewhere. This should really be in the standard lib.
// We need it for the sake of type inference.
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> items)
{
    return new HashSet<T>(items);
}

var shared = foos.Select(foo => new { foo.SharedProperty1, foo.SharedProperty2 })
                 .ToHashSet();

var query = bars.Where(bar => shared.Contains(new { bar.SharedProperty1,
                                                    bar.SharedProperty2 }));

使用連接的其他選項肯定會起作用 - 但我發現這更清楚,因為你只想看一次每個bar ,即使有幾個具有該屬性的foo項。

聽起來你需要加入:

var fooList = new List<foo>();
var barList = new List<bar>();

// fill the lists

var results = from f in fooList
              join b in barList on 
                  new { f.commonPropery1, f.commonProperty2 }
                  equals 
                  new { b.commonProperty1, commonProperty2 = b.someOtherProp }
              select new { f, b };

Any應該工作,如果它與多少foo的匹配無關:

var selectedBars = bars.Where(bar => 
                                foos.Any(foo => foo.Property1 == bar.Property1 
                                             && foo.Property2 == bar.Property2));

如果所有foos都匹配使用All

var selectedBars = bars.Where(bar => 
                                foos.All(foo => foo.Property1 == bar.Property1 
                                             && foo.Property2 == bar.Property2));

如果foos列表很大,請使用John Skeets中指出的HashSet答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM