简体   繁体   English

使用linq从列表中获得不同的值

[英]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如下实现:

  1. Get the Nuget Package 获取Nuget软件包

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: 重要事项:

  1. ColArray can be modified to have 1 or more than 1 column, it will automatically adjust 可以将ColArray修改为具有1列或多于1列,它将自动调整
  2. Grouping key by default is a DynamicClass , and grouped value is an obj class type 默认情况下,分组键是DynamicClass ,分组值是obj class类型
  3. "it" in grouping statement is Dynamic Linq keyword for selecting all the Columns, instead of specific columns 分组语句中的“ it”是Dynamic Linq关键字,用于选择所有列,而不是特定列

Result: 结果:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM