这是从LinqPad(因此.Dump())

void Main()
{
    var k1 = new List<int>(){1,2,3,4,5};
    var k2 = new List<int>(){1,2,3,4,5};

    var o1 = new A(){k=k1, objectName="o1"};
    var o2 = new A(){k=k2, objectName="o2"};

    var l = new List<A>();

    l.Add(o1);
    l.Add(o2);

    var b = from a in l
    group a.objectName by a.k into g
    select new {g.Key, n = String.Join(",",g)};

    b.Dump();
}

public class A {
    public List<int> k;
    public string objectName;
}


问题是它不起作用,上面的代码产生:

c# - 按键将list &lt;int&gt;用作linq组-LMLPHP

我知道为什么会这样,这是因为列表对象是单独的对象,但是我想知道的是,是否有一种方法可以告诉group by使用列表的内容而不是对象实例。

最佳答案

public static void Main()
{
    var k1 = new List<int>(){1,2,3,4,5};
    var k2 = new List<int>(){1,2,3,4,5};

    var o1 = new A(){k=k1, objectName="o1"};
    var o2 = new A(){k=k2, objectName="o2"};

    var l = new List<A>();

    l.Add(o1);
    l.Add(o2);

    // Use custom comparer for the list
    var b = l.GroupBy(a => a.k, new ListComparer<int>())
             .Select(g => new
                {
                    Key = String.Join(",", g.Key.Select(i => i)),
                    n = String.Join(",",g.Select(i => i.objectName))
                });


    foreach(var item in b)
    {
        Console.WriteLine(string.Format("{0} : {1}", item.Key, item.n));
        // 1,2,3,4,5 : o1,o2
    }
}

public class A
{
    public List<int> k;
    public string objectName;
}


public class ListComparer<T> : IEqualityComparer<List<T>>
{
    // Ignore the order and compare with the sequence value for the equality
    public bool Equals(List<T> left, List<T> right)
    {
        return left.OrderBy(i => i).SequenceEqual(right.OrderBy(i => i));
    }

    public int GetHashCode(List<T> list)
    {
        return list.Count;
    }
}


.Net Fiddle

关于c# - 按键将list <int>用作linq组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31736985/

10-16 08:55