我有一个对象列表,我希望根据数组从中获取另一个不同值的列表。
用示例解释我的问题
原始列表
// 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);
现在我想要另一个列表,它具有不同的值,具体取决于数组
string[] ColArray = new string[2] {"Name", "Surname"};
我该怎么办?基本上有另一个列表,其中包含数组中不同的列
List<Obj> NewList = objects.GroupBy( what to put here ).Select(x => x.First()).ToList();
我的NewList将包含a和b
的对象答案 0 :(得分:2)
您可以使用System.Linq.Dynamic
完成此操作,如下所示:
以下是代码(在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();
}
要点: