如何通过 Lambda 或 LINQ 从列表中获取不同的实例 [英] How to get distinct instance from a list by Lambda or LINQ
问题描述
我有一堂这样的课:
class MyClass<T> {
public string value1 { get; set; }
public T objT { get; set; }
}
和这个类的列表.我想使用 .net 3.5 lambda 或 linq 通过不同的 value1 获取 MyClass 列表.我想这是可能的,而且比 .net 2.0 中缓存这样的列表的方法简单得多:
and a list of this class. I would like to use .net 3.5 lambda or linq to get a list of MyClass by distinct value1. I guess this is possible and much simpler than the way in .net 2.0 to cache a list like this:
List<MyClass<T>> list;
...
List<MyClass<T>> listDistinct = new List<MyClass<T>>();
foreach (MyClass<T> instance in list)
{
// some code to check if listDistinct does contain obj with intance.Value1
// then listDistinct.Add(instance);
}
使用 lambda 或 LINQ 的方法是什么?
What is the lambda or LINQ way to do it?
推荐答案
Marc 和 dahlbyk 的答案似乎都非常有效.不过,我有一个更简单的解决方案.您可以使用 GroupBy
而不是使用 Distinct
.它是这样的:
Both Marc's and dahlbyk's answers seems to work very well. I have a much simpler solution though. Instead of using Distinct
, you can use GroupBy
. It goes like this:
var listDistinct
= list.GroupBy(
i => i.value1,
(key, group) => group.First()
).ToArray();
请注意,我已将两个函数传递给 GroupBy()
.第一个是键选择器.第二个从每组中只得到一个项目.根据您的问题,我认为 First()
是正确的.如果你愿意,你可以写一个不同的.你可以试试 Last()
看看我的意思.
Notice that I've passed two functions to the GroupBy()
. The first is a key selector. The second gets only one item from each group. From your question, I assumed First()
was the right one. You can write a different one, if you want to. You can try Last()
to see what I mean.
我使用以下输入进行了测试:
I ran a test with the following input:
var list = new [] {
new { value1 = "ABC", objT = 0 },
new { value1 = "ABC", objT = 1 },
new { value1 = "123", objT = 2 },
new { value1 = "123", objT = 3 },
new { value1 = "FOO", objT = 4 },
new { value1 = "BAR", objT = 5 },
new { value1 = "BAR", objT = 6 },
new { value1 = "BAR", objT = 7 },
new { value1 = "UGH", objT = 8 },
};
结果是:
//{ value1 = ABC, objT = 0 }
//{ value1 = 123, objT = 2 }
//{ value1 = FOO, objT = 4 }
//{ value1 = BAR, objT = 5 }
//{ value1 = UGH, objT = 8 }
我还没有测试它的性能.我相信这个解决方案可能比使用 Distinct
的解决方案慢一点.尽管有这个缺点,但有两个很大的优点:简单性和灵活性.通常,更倾向于简单而不是优化,但这实际上取决于您要解决的问题.
I haven't tested it for performance. I believe that this solution is probably a little bit slower than one that uses Distinct
. Despite this disadvantage, there are two great advantages: simplicity and flexibility. Usually, it better to favor simplicity over optimization, but it really depends on the problem you're trying to solve.
这篇关于如何通过 Lambda 或 LINQ 从列表中获取不同的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!