C# 在列表中选择两个不同的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11811110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select distinct by two properties in a list
提问by user1304444
I have a list<message>that contains properties of type Guidand DateTime(as well as other properties). I would like to get rid of all of the items in that list where the Guidand DateTimeare the same (except one). There will be times when those two properties will be the same as other items in the list, but the other properties will be different, so I can't just use .Distinct()
我有一个list<message>包含类型Guid和DateTime(以及其他属性)的属性。我想删除该列表中Guid和DateTime相同的所有项目(一个除外)。有时这两个属性会与列表中的其他项目相同,但其他属性会不同,所以我不能只使用.Distinct()
List<Message> messages = GetList();
//The list now contains many objects, it is ordered by the DateTime property
messages = from p in messages.Distinct( what goes here? );
This is what I have right now, but it seems like there ought to be a better way
这就是我现在所拥有的,但似乎应该有更好的方法
List<Message> messages = GetList();
for(int i = 0; i < messages.Count() - 1) //use Messages.Count() -1 because the last one has nothing after it to compare to
{
if(messages[i].id == messages[i+1}.id && messages[i].date == message[i+1].date)
{
messages.RemoveAt(i+1);
{
else
{
i++
}
}
采纳答案by Jon Skeet
回答by Andrew Church
What about this?
那这个呢?
var messages = messages
.GroupBy(m => m.id)
.GroupBy(m => m.date)
.Select(m => m.First());
回答by Adam
Jon Skeet's DistinctByis definitely the way to go, however if you are interested in defining your own extension method you might take fancy in this more concise version:
Jon Skeet 的DistinctBy绝对是要走的路,但是如果您有兴趣定义自己的扩展方法,您可能会喜欢这个更简洁的版本:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
var known = new HashSet<TKey>();
return source.Where(element => known.Add(keySelector(element)));
}
which has the same signature:
具有相同的签名:
messages = messages.DistinctBy(x => new { x.id, x.date }).ToList();
回答by Andrzej Gis
You can check out my PowerfulExtensionslibrary. Currently it's in a very young stage, but already you can use methods like Distinct, Union, Intersect, Except on any number of properties;
你可以查看我的强大扩展库。目前它处于非常年轻的阶段,但你已经可以在任意数量的属性上使用 Distinct、Union、Intersect、Except 等方法;
This is how you use it:
这是你如何使用它:
using PowerfulExtensions.Linq;
...
var distinct = myArray.Distinct(x => x.A, x => x.B);
回答by Manish Agarwal
Try this,
尝试这个,
var messages = (from g1 in messages.GroupBy(s => s.id) from g2 in g1.GroupBy(s => s.date) select g2.First()).ToList();

