Reputation: 873
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?
Upvotes: 0
Views: 372
Reputation: 125620
SelectMany
is what you're looking for:
var res = A.listB.SelectMany(b => b.C).Select(c => c.D).Distinct().ToList();
Upvotes: 2