如何在对象列表中获得组合
本文关键字:组合 列表 对象 | 更新日期: 2023-09-27 18:13:37
我有一个对象列表:
List<classname> mylist=new List<classname>();
public class classname
{
public String test { set; get; }
public String name { set; get; }
public String value{ set; get; }
}
我的列表包含以下值:
test1, name1, value1
test1, name2, value2
test2, name1, value1
test2, name3, value3
test3, name4, value4
我需要得到组合,其中每个组合都有一个值列表,如
test1, name1, value1
test2, name1, value1
test3, name1, value3
每个组合应该包含test1
, test2
和test3
中的一行
看起来您想按classname.name分组,在这种情况下,您可以这样做
void Main()
{
List<classname> mylist=new List<classname>()
{
new classname { test = "test1", name = "name1", value = "value1" },
new classname { test = "test1", name = "name2", value = "value2" },
new classname { test = "test2", name = "name1", value = "value1" },
new classname { test = "test2", name = "name1", value = "value3" },
new classname { test = "test2", name = "name3", value = "value3" },
new classname { test = "test3", name = "name4", value = "value4" }
};
var groups = mylist.GroupBy(x => x.name);
foreach(var group in groups)
{
// name property value
//Console.WriteLine(group.Key);
foreach(var row in group)
{
// unique rows for this "name" group
Console.WriteLine($"{row.test} {group.Key} {row.value}");
}
Console.WriteLine();
}
}
public class classname
{
public String test { set; get; }
public String name { set; get; }
public String value{ set; get; }
}
输出:test1 name1 value1
test2 name1 value1
test2 name1 value3
test1 name2 value2
test2 name3 value3
test3 name4 value4