返回对象数组的不同列表,其中数组项的数目是不特定的
本文关键字:数组 对象 列表 返回 | 更新日期: 2023-09-27 18:22:13
有没有一种方法可以使用LINQ从对象数组列表中获取不同的项列表,而不知道每个数组中有多少项?在整个列表中,每个数组项中的项数都是相同的。
// Foo is a list of object arrays. The number of items
// each array is non-specific.
// (In this example there is only 3 items, but there could be 100)
var foo = new List<object[]>();
// I add some items to the list.
foo.Add(new object[] { 1, "Something", true });
foo.Add(new object[] { 1, "Some Other", false });
foo.Add(new object[] { 2, "Something", false });
foo.Add(new object[] { 2, "Something", false });
// This will get me a distinct list from the array list...
// but it requires I know how many items are in each array.
List<object[]> bar = foo.Select(x => new { X1 = x[0], X2 = x[1], X3 = x[2] })
.Distinct()
.Select(x => new object[] { x.X1, x.X2, x.X3 })
.ToList();
List<object[]> bar = ?? /// < -- How can I rewrite the
// previous line so that
// my code works with n array items?
如果有帮助的话,我会知道运行时有多少项?
如果这在LINQ中是不可能的,有人能建议我可以使用的方法来实现期望的结果吗?
如果我理解你的意思,那么你可以试试这样的东西:
class Comparer : IEqualityComparer<object[]>
{
public bool Equals(object[] x, object[] y)
{
if (x.Length != y.Length)
return false;
for (int i = 0; i < x.Length; ++i)
if (!x[i].Equals(y[i]))
return false;
return true;
}
public int GetHashCode(object[] obj)
{
return string.Join("", obj).GetHashCode();
}
}
static void Main(string[] args)
{
var foo = new List<object[]>();
foo.Add(new object[] { 1, "Something", true });
foo.Add(new object[] { 1, "Some Other", false });
foo.Add(new object[] { 2, "Something", false });
foo.Add(new object[] { 2, "Something", false });
var distinctList = foo.Distinct(new Comparer()).ToList();
/*
distinctList now contains
1, "Something", true
1, "Some Other", false
2, "Something", false
*/
}
请尝试使用以下代码
List<object[]> bar = foo.GroupBy(x => new { X1 = x[0], X2 = x[1], X3 = x[2] }).Select(g => new object[] { g.Key.X1, g.Key.X2, g.Key.X3, g.Count() }).ToList();
每个对象有四个值,最后一个值用于组的计数