[英]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 我的NewList将包含a和b的对象
You can achieve it using System.Linq.Dynamic
as follows: 您可以使用
System.Linq.Dynamic
如下实现:
Following would be the code (On LinqPad, otherwise replace Dump
call with Console.WriteLine
): 以下是代码(在LinqPad上,否则将
Dump
调用替换为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
type DynamicClass
,分组值是obj class
类型 Result: 结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.