简体   繁体   中英

How to get grouping result as a list from the enumerable list?

How do I get unique records from list?

public class VinDecoded
{
    public string SquishVin {get;set;} = "";
    public string Year {get;set;} = "";
    public string Make {get;set;} = "";
}
var modelVinDecodeds = new List<VinDecoded>();

modelVinDecodeds.Add(new VinDecoded() {SquishVin="1234",Year="2007",Make="Ford"});
modelVinDecodeds.Add(new VinDecoded() {SquishVin="2233",Year="2010",Make="Chevy"});
modelVinDecodeds.Add(new VinDecoded() {SquishVin="2233",Year="2010",Make="GMC"});

In this case, I want to get custom List<VinDecoded>() having only the matching SquishVin of "2233".

This I tried which don't work. I'm getting Key and no List. I only want the List<VinDecoded>() data where there's no List.

var modelCustomVinDecoded = modelVinDecodeds.GroupBy(x => x.SquishVin).ToList();

foreach(var v in modelCustomVinDecoded)
{
    if (v.Key != "0033")
    {
         FooSave(v.???);   //Where's the list coming from the v part?
    }
}

GroupBy(x => x.SquishVin) will returns an IEnumerable<IGrouping<string, VinDecoded>> and IGrouping<string, VinDecoded> have a property called Key returning the SquishVin in all VinDecoded objects in the group. Also IGrouping<string, VinDecoded> is an IEnumerable<VinDecode> , so you can iterate it or just convert it to a list.

You can do this:

var modelCustomVinDecoded = modelVinDecodeds.GroupBy(x => x.SquishVin).ToList();

foreach(var v in modelCustomVinDecoded)
{
    if (v.Key != "0033")
    {
        FooSave(v.ToList());
    }
}

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