gpt4 book ai didi

c# - 按键使用 list 作为 linq 组

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:35 25 4
gpt4 key购买 nike

这是来自 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;
}

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

enter image description here

我知道为什么会这样,因为列表对象是单独的对象,但我想知道是否有办法告诉 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com