Filter IEnumerable against IEnumerable

2019-02-24 12:49发布

I have an object Style with a property StockNumber. I would like to filter a list of all Db.Styles against an IEnumerable<string> stockNumbers the user enters in a search. DB.Styles is an IEnumerable<Style>. Here is essentially what I am trying to do:

public IEnumerable<Style> LoadListOfStyles(IEnumerable<string> stockNumbers)
{
    return Db.Styles.Intersect(stockNumbers);
    // Need to filter Db.Styles based on stockNumbers
}

So is there an easy way to compare the list of all styles in Db.Styles against my search values in stockNumbers to return a filtered list of only the Styles the user has searched for? The only way I have seen to be able to do this is to have 2 IEnumerable objects to intersect, but loading the styles one by one from the stock numbers searched seems like a lot of unnecessary code. I am wondering if there is an easier way. Or do I need to roll my own method to filter the results?

4条回答
神经病院院长
2楼-- · 2019-02-24 13:24
public IEnumerable<Style> LoadListOfStyles(List<string> stockNumbers)
{
    return db.Styles.Where(s => stockNumbers.Contains(s.StockNumber));
}
查看更多
3楼-- · 2019-02-24 13:30

You can think of Intersect as effectively a Join where the keys of each object are always "themselves". Here you want to perform a join where the key isn't always "itself", so you use a Join (or, if you need to remove duplicates, a GroupJoin).

var query = from style in Db.Styles
    join number in stockNumbers
    on style.StockNumber equals number
    into numbers
    where numbers.Any()
    select style;
查看更多
可以哭但决不认输i
4楼-- · 2019-02-24 13:32

Consider a Where clause.

public IEnumerable<Style> LoadListOfStyles(IEnumerable<string> stockNumbers)
{
    return Db.Styles.Where(style => !stockNumbers.Contains(style.StockNumber));
}
查看更多
Bombasti
5楼-- · 2019-02-24 13:50
return db.Styles.Where(style => stockNumbers.Any(sn => sn == style.StockNumber));
查看更多
登录 后发表回答