Reputation: 1999
Is there a way using LINQ to get a distinct list of items from a list of object array without knowing how many items exist in each array? The number of items in each array item will be the same throughout the list.
// 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?
I will know how many items there are at runtime if that helps?
If it is not possible in LINQ, can anyone please suggest a method I could use to achieve the desired results?
Upvotes: 4
Views: 2704
Reputation: 567
If i understand you right then you can try something like this:
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
*/
}
Upvotes: 4
Reputation: 2045
Please try with below code
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();
Each object has four value and last one for count of group
Upvotes: -1