开发者

how I can obtain objects from a generic list with Linq where properties of objects = xyz grouping by another property

I'm learning Linq. I not sure how I can select data from a generic list.

in the next pseudo-code example, I like to group into a new class by "data", making a list of "type", and selecting id (same id for same data)

List<MyClass>

MyCla开发者_开发问答ss have:
-------------
string id
string type
string data

example of instances (all of this contained in a List<MyClass>

MyClass1
--------
id   = "a"
type = "a"
data = "someData1"

MyClass2
--------
id   = "a"
type = "b"
data = "someData1"

MyClass3
--------
id   = "b"
type = "c"
data = "someData2"

MyClass4
--------
id   = "b"
type = "b"
data = "someData2"

MyClass5
--------
id   = "a"
type = "c"
data = "someData1"

I like to obtain something like:

MyNewClassX
id    = "a"
types =  {"a","b","c"} 
data  = "someData1"

MyNewClassY
id    = "b"
types = {"c","z"}
data = "someData2"

And later... I like to obtain -for example- MyNewclasses where type = "c"

I not sure if is good idea to group to obtain that result or I have to use another Linq query to select the data I want.


var q1 = from m in list
         group m by m.data into g
         select new {g.First().id, types=g.Select(_=>_.type), data=g.Key};

//selects by type
var q2 = from m in q1
         where m.types.Contains("c")
         select m;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜