简体   繁体   English

比较两个列表与LINQ更好的方法?

[英]Better way of comparing two lists with LINQ?

I have the 2 collections: 我有2个收藏夹:

IEnumerable<Element> allElements
List<ElementId> someElements, 

What is a concise way of doing the following together: 一起执行以下操作的简洁方式是什么:

[1] Verifying that all elements in someElements exist in allElements , return quickly when condition fails. [1]验证someElements中的所有元素都存在于allElements ,当条件失败时会快速返回。

and

[2] Obtain a list of Element objects that List<ElementId> someElements maps to. [2]获取List<ElementId> someElements映射到的Element对象的List<ElementId> someElements

Every Element object has an ElementId 每个Element对象都有一个ElementId

Thank you. 谢谢。

I would do this: 我会这样做:

var map = allElements.ToDictionary(x => x.Id);    
if (!someElements.All(id => map.ContainsKey(id))
{
    // Return early
}
var list = someElements.Select(x => map[x])
                       .ToList();

Note that the first line will throw an exception if there are any duplicates in allElements . 请注意,如果allElements有任何重复项,第一行将引发异常。

  1. someElements.All(e => allElements.Contains(e));
  2. allElements.Where(e => someElements.Contains(e.ElementId));

Not as efficient as the Skeet answer, but good enough for reasonable-sized collections: 效率不及Skeet答案,但对于合理大小的集合来说足够好:

IEnumerable<Element> allElements = new List<Element>
    { new Element { Id = 1 }, new Element { Id = 2 } };
List<int> someElements = new List<int> { 1, 2 };

var query =
    (from element in allElements
    join id in someElements on element.Id equals id
    select element)
    .ToList();

if (query.Count != someElements.Count)
{
    Console.WriteLine("Not all items found.");
}

foreach (var element in query)
{
    Console.WriteLine ("Found: " + element.Id);
}

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

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