简体   繁体   English

如何检查一个列表是否包含另一个列表C#

[英]how to check that a list contains another list C#

I have two List of domain entities, 我有两个域实体列表,

First one is Item List, Structure: 第一个是项目列表,结构:

string ItemID;
string ItemName;
int Qty;
double price;

Another one is Offer List, Structure: 另一个是要约清单,结构:

int OfferID;
string ItemID;
int OfferPrice;

Having two variables like this, 有两个这样的变量,

List<DomainEntities.Items> ItemList=new List<DomainEntities.Items>();
List<DomainEntities.Offers> OfferList=new List<DomainEntities.Offers>();

Now i wanted to filter from ItemList.ItemID property which contains OfferList.ItemID, Output should be List. 现在我想从包含OfferList.ItemID的ItemList.ItemID属性进行过滤,输出应为List。

How to do this filtration? 如何进行过滤? Thanks! 谢谢!

You can do this 你可以这样做

ItemList.Where(item => OfferList.Any(offer => offer.ItemID == item.ItemID)).ToList();

You can also do this (may perform faster) 您也可以这样做(可能执行得更快)

ItemList.Join(OfferList, item => item.ItemID, offer => offer.ItemID, (item, offer) => item).ToList();

If the lists get large (more than 100 elements each), you should look into a faster lookup strategy, such as the one offered by HashSet<T> . 如果列表变大(每个列表超过100个元素),则应研究一种更快的查找策略,例如HashSet<T>提供的策略。

List<DomainEntities.Items> itemList = new List<DomainEntities.Items>();
List<DomainEntities.Offers> offerList = new List<DomainEntities.Offers>();

var offerSet = new HashSet<string>(offerList.Select(o => o.ItemID));
var output = itemList.Where(item => offerSet.Contains(item.ItemID)).ToList();

The advantage of HashSet<T> is that it offers constant performance on lookups, irrespective of its size. HashSet<T>的优点在于,无论其大小如何,它都能提供恒定的查询性能。 Thus, if itemList contains m elements and offerList contains n elements, the code above will require roughly n operations to build the hash set, but then only takes 1 step to compare any item against it. 因此,如果itemList包含m个元素,而offerList包含n个元素,则上面的代码将需要大约n个操作来构建哈希集,但是仅需一步就可以将任何项目与其进行比较。 Thus, it would take a total of m steps to filter all elements of itemList against it. 因此,总共需要m步来针对它过滤itemList所有元素。

By contrast, calling offerList.Any requires iterating through its elements each time, effectively resulting in a nested loop. 相比之下,调用offerList.Any需要遍历其元素,从而有效地导致了嵌套循环。 Thus, that approach would require a total of m × n steps, rather than m + n . 因此,该方法将需要总共m × n个步骤,而不是m + n 步骤。 This becomes significant for large collections -- if the two lists contain 1,000 elements each, the HashSet<T> approach would take 2,000 steps, whilst the nested loop would take 1,000,000 steps. 对于大型集合而言,这变得很重要-如果两个列表每个都包含1,000个元素,则HashSet<T>方法将花费2,000步,而嵌套循环将花费1,000,000步。 (I am using the term "steps" loosely here; I'm actually referring to algorithmic complexity .) (我在这里宽松地使用了“步骤”一词;实际上是指算法的复杂性 。)

The Join operator offers a similar optimization to HashSet<T> under the hood. Join运算符提供了与HashSet<T>类似的优化。

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

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