简体   繁体   中英

C# - LINQ select distinct from list which contain list

Ok, here's what I have.

public class A
{
    //Properties

    List<B> listB;

    //Methods
}

public class B
{
    //Properties

    public struct C
    {
        public byte D
        {
            get;
            set;
        }

        //Other propeties
    }

    public List<C> listC;

    //Methods
}


//..somewhere
A mydataA = new A();
mydataA.listB = new List<B>();
mydataA.listB.listC = new List<C>();

mydataA.listB.listC = JsonConvert.DeserializeObject<List<C>>(json);
//C.D will take values like 1, 2, 1, 2, 2, 3, 5, 2

I need to select distinct values of D from each C , so result will be list of 1, 2, 3, 5 . For now, I'm selecting distinct data like this:

List<byte> mylist = new List<byte>();
foreach(var each_of_B in A.listB)
{
    foreach(var each_of_C in each_of_B.C)
    {
        mylist.Add(each_of_C.D);
    }
}

var res = mylist.GroupBy(t => t).Select(g => g.First()).ToList();

But it's not really cool, because I have to create new List, create some loops. Is there any way to select distinct data with one line, smth like var res = mydataA.***.Select(g => g.First()).ToList(); , where *** is what I need?

SelectMany是您要找的东西:

var res = A.listB.SelectMany(b => b.C).Select(c => c.D).Distinct().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