user2837961
user2837961

Reputation: 1555

Distinct values from a list using linq

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

Answers (1)

Mrinal Kamboj
Mrinal Kamboj

Reputation: 11482

You can achieve it using System.Linq.Dynamic as follows:

  1. Get the Nuget Package

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:

  1. ColArray can be modified to have 1 or more than 1 column, it will automatically adjust
  2. Grouping key by default is a DynamicClass, and grouped value is an obj class type
  3. "it" in grouping statement is Dynamic Linq keyword for selecting all the Columns, instead of specific columns

Result:

enter image description here

Upvotes: 2

Related Questions