如何在对象列表中获取组合?

时间:2016-10-18 12:14:01

标签: c# list combinations

我有一个对象列表:

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

每个组合应包含test1test2test3

中的一行

1 个答案:

答案 0 :(得分:0)

看起来你想按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