简体   繁体   English

C#LINQ比较列表值

[英]C# LINQ comparing list values

I have two List of two different custom types. 我有两个不同自定义类型的列表。 Both types share 2 common properties. 两种类型共享2个共同属性。

For example: 例如:

List<foo>;
List<bar>;

They both have properties, for example, named Name and Age. 它们都具有属性,例如名为Name和Age。

I want to return a new List containing all bar objects, where the Name and Age properties of bar are present in any of the foo objects. 我想返回一个包含所有bar对象的新List,其中bar的Name和Age属性出现在任何foo对象中。 What would be the best way to do this? 最好的方法是什么?

Thanks 谢谢

Assuming the shared properties implement equality etc properly, you might want to do something like: 假设共享属性正确实现了相等,您可能希望执行以下操作:

// 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 }));

The other options using joins will certainly work - but I find this clearer for the expressing the idea that you only want to look at each bar entry once, even if there are several foo items with that property. 使用连接的其他选项肯定会起作用 - 但我发现这更清楚,因为你只想看一次每个bar ,即使有几个具有该属性的foo项。

Sounds like you need a join: 听起来你需要加入:

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 should work if it's irrelevant how many foo's match: Any应该工作,如果它与多少foo的匹配无关:

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

If all foos should match use All 如果所有foos都匹配使用All

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

If the list of foos is large use a HashSet as pointed out in John Skeets answer. 如果foos列表很大,请使用John Skeets中指出的HashSet答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM