1

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

6
  • Do you want to distinct objects value? Commented Apr 12, 2017 at 10:42
  • Yes I want distinct objects depending on the column values. The columns are defined in the array Commented Apr 12, 2017 at 10:44
  • Distinct on what column, name field alone Commented Apr 12, 2017 at 10:44
  • Check stackoverflow.com/questions/17678197/linq-grouping-dynamically Commented Apr 12, 2017 at 10:44
  • No - all columns defined in the array. The array values are defined runtime. Commented Apr 12, 2017 at 10:45

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.