Reputation: 1555
I have a list of objects from which I want another list of distinct values depending on an array.
To explain my problem with an example
Original List
// Class of the object
class Obj
{
public string Name { get; set; }
public string Surname { get; set; }
public string Address { get; set; }
}
// List of the object
List<Obj> objects = new List<Obj>();
//Values in the list
Obj a = new Obj();
a.Name = "Jack";
a.Surname = "Grey";
a.Address = "Sheffield";
objects.Add(a);
Obj b = new Obj();
b.Name = "John";
b.Surname = "Grey";
b.Address = "Sheffield";
objects.Add(b);
Obj c = new Obj();
c.Name = "Jack";
c.Surname = "Grey";
c.Address = "London";
objects.Add(c);
Now I want another list which would have distinct values depending upon an array
string[] ColArray = new string[2] {"Name", "Surname"};
How can I do something like this? Basically have another list with distinct columns from the array
List<Obj> NewList = objects.GroupBy( what to put here ).Select(x => x.First()).ToList();
My NewList would contain objects of a and b
Upvotes: 1
Views: 451
Reputation: 11482
You can achieve it using System.Linq.Dynamic
as follows:
Following would be the code (On LinqPad, otherwise replace Dump
call with Console.WriteLine
):
string[] ColArray = new string[] {"Name","Surname"};
string groupingString = "new(" + string.Join(",",ColArray) + ")";
var groupedObjectData = objects.GroupBy(groupingString,"it");
foreach (IGrouping<DynamicClass, Obj> objGroup in groupedObjectData)
{
objGroup.Select(x => x).Dump();
}
Important Points:
DynamicClass
, and grouped value is an obj class
typeResult:
Upvotes: 2