简体   繁体   中英

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?

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

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

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.

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

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;

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.

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