Вопрос:

Filter IEnumerable<T> against IEnumerable<string>

c# linq entity-framework lambda

222 просмотра

4 ответа

63 Репутация автора

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?

Автор: CoolCriSyS Источник Размещён: 16.07.2014 02:21

Ответы (4)


1 плюс

27596 Репутация автора

public IEnumerable<Style> LoadListOfStyles(List<string> stockNumbers)
{
    return db.Styles.Where(s => stockNumbers.Contains(s.StockNumber));
}
Автор: Sam I am says Reinstate Monica Размещён: 16.07.2014 02:24

1 плюс

23340 Репутация автора

Consider a Where clause.

public IEnumerable<Style> LoadListOfStyles(IEnumerable<string> stockNumbers)
{
    return Db.Styles.Where(style => !stockNumbers.Contains(style.StockNumber));
}
Автор: Bas Размещён: 16.07.2014 02:24

1 плюс

12977 Репутация автора

Решение
return db.Styles.Where(style => stockNumbers.Any(sn => sn == style.StockNumber));
Автор: Yuliam Chandra Размещён: 16.07.2014 02:25

1 плюс

183441 Репутация автора

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;
Автор: Servy Размещён: 16.07.2014 02:26
Вопросы из категории :
32x32