如何从Linq获取通用列表中的对象,其中对象的属性= xyz由另一个属性分组

时间:2011-04-16 03:35:53

标签: .net linq-to-objects

我正在学习Linq。 我不确定如何从通用列表中选择数据。

在下一个伪代码示例中,我喜欢按“数据”分组到新类,制作“类型”列表,并选择id(相同数据的相同ID)

List<MyClass>

MyClass 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"

我喜欢这样的东西:

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

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

后来......我想获得 - 例如 - MyNewclasses,其中type =“c”

我不确定分组获取结果是否是个好主意,或者我必须使用另一个Linq查询来选择我想要的数据。

1 个答案:

答案 0 :(得分:2)

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;