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.
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>
.
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. 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. Thus, it would take a total of m steps to filter all elements of itemList
against it.
By contrast, calling offerList.Any
requires iterating through its elements each time, effectively resulting in a nested loop. Thus, that approach would require a total of m × n steps, rather than 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. (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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.