jazza1000
jazza1000

Reputation: 4247

how to use linq to retrieve values from a 2 dimensional generic list

I have a generic List List[int, myClass], and I would like to find the smallest int value, and retrieve the items from the list that match this.

I am generating this from another LINQ statement

var traysWithExtraAisles = (from t in poolTrays
                            where t.TrayItems.Select(i=>i.Aisle)
                            .Any(a=> ! selectedAisles.Contains(a))
                           select new
                           {
                             count= t.TrayItems.Select(i=>i.Aisle)
                                     .Count(a=> !selectedAisles.Contains(a)),
                             tray=t
                            }).ToList();

this gives me my anonymous List of [count, Tray], but now I want to figure out the smallest count, and return a sublist for all the counts that match this.

Can anyone help me out with this?

Upvotes: 1

Views: 358

Answers (4)

King King
King King

Reputation: 63357

You can use GroupBy as answered by Tim... or OrderBy as follow:

var result = traysWithExtraAisles.OrderBy(x=>x.count)
                                 .TakeWhile((x,i)=> i == 0 || x.count == traysWithExtraAisles[i-1]).count;

Upvotes: -1

jazza1000
jazza1000

Reputation: 4247

Right, I now realise this is actually incredibly easy to do with a bit more fiddling around. I have gone with

int minCount = traysWithExtraAisles.Min(x=>x.count);
var minAislesList = (from t in trayswithExtraAisles
                     where t.count==mincount
                     select t).ToList()

I imagine it is probably possible to do this in one statement

Upvotes: 0

evanmcdonnal
evanmcdonnal

Reputation: 48114

You can use SelectMany to "flatten" your list. Meaning, combine all of the lists into one, then take the Min. So;

  int minimum = poolTrays.SelectMany(x => x).Min(x => x.TheIntegerIWantMinOf);

Will give you the smallest value contained in the sub lists. I'm not entirely sure this is what you're asking for but if your goal is simply to find the smallest element in the collection then I would scrap the code you posted and use this instead.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460238

var smallestGroup = traysWithExtraAisles
    .GroupBy(x => x.count)
    .OrderBy(g => g.Key)
    .First();

foreach(var x in smallestGroup)
{
    var poolTray = x.tray;
}

Upvotes: 2

Related Questions