在 C# 中从列表中选择唯一元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/292307/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:56:46  来源:igfitidea点击:

Selecting Unique Elements From a List in C#

c#list

提问by Ozgur Ozcitak

How do I select the unique elements from the list {0, 1, 2, 2, 2, 3, 4, 4, 5}so that I get {0, 1, 3, 5}, effectively removing all instances ofthe repeated elements {2, 4}?

如何从列表中选择唯一元素,{0, 1, 2, 2, 2, 3, 4, 4, 5}以便{0, 1, 3, 5}有效地删除重复元素的所有实例{2, 4}

采纳答案by Bryan Watts

var numbers = new[] { 0, 1, 2, 2, 2, 3, 4, 4, 5 };

var uniqueNumbers =
    from n in numbers
    group n by n into nGroup
    where nGroup.Count() == 1
    select nGroup.Key;

// { 0, 1, 3, 5 }

回答by CVertex

var nums = new int{ 0...4,4,5};
var distinct = nums.Distinct();

make sure you're using Linq and .NET framework 3.5.

确保您使用的是 Linq 和 .NET 框架 3.5。

回答by Corey Trager

If Linq isn't available to you because you have to support legacy code that can't be upgraded, then declare a Dictionary, where the first int is the number and the second int is the number of occurences. Loop through your List, loading up your Dictionary. When you're done, loop through your Dictionary selecting only those elements where the number of occurences is 1.

如果由于您必须支持无法升级的遗留代码而无法使用 Linq,则声明一个 Dictionary,其中第一个 int 是数字,第二个 int 是出现次数。循环浏览您的列表,加载您的词典。完成后,循环遍历字典,仅选择出现次数为 1 的元素。

回答by Matt Howells

C# 2.0 solution:

C# 2.0 解决方案:

static IEnumerable<T> GetUniques<T>(IEnumerable<T> things)
{
    Dictionary<T, int> counts = new Dictionary<T, int>();

    foreach (T item in things)
    {
        int count;
        if (counts.TryGetValue(item, out count))
            counts[item] = ++count;
        else
            counts.Add(item, 1);
    }

    foreach (KeyValuePair<T, int> kvp in counts)
    {
        if (kvp.Value == 1)
            yield return kvp.Key;
    }
}

回答by Robert Rossney

I believe Matt meant to say:

我相信马特的意思是:

 static IEnumerable<T> GetUniques<T>(IEnumerable<T> things)
 {
     Dictionary<T, bool> uniques = new Dictionary<T, bool>();
     foreach (T item in things)
     {
         if (!(uniques.ContainsKey(item)))
         {
             uniques.Add(item, true);
         }
     }
     return uniques.Keys;
 }

回答by Barbaros Alp

With lambda..

与拉姆达..

var all = new[] {0,1,1,2,3,4,4,4,5,6,7,8,8}.ToList();
var unique = all.GroupBy(i => i).Where(i => i.Count() == 1).Select(i=>i.Key);

回答by Murilo Beltrame

In .Net 2.0 I`m pretty sure about this solution:

在 .Net 2.0 中,我非常确定这个解决方案:

public IEnumerable<T> Distinct<T>(IEnumerable<T> source)
{
     List<T> uniques = new List<T>();
     foreach (T item in source)
     {
         if (!uniques.Contains(item)) uniques.Add(item);
     }
     return uniques;
}

回答by Ewald Stieger

Here is another way that works if you have complex type objects in your List and want to get the unique values of a property:

如果您的 List 中有复杂类型的对象并且想要获取属性的唯一值,那么这是另一种有效的方法:

var uniqueValues= myItems.Select(k => k.MyProperty)
                  .GroupBy(g => g)
                  .Where(c => c.Count() == 1)
                  .Select(k => k.Key)
                  .ToList();

Or to get distinct values:

或获得不同的值:

var distinctValues = myItems.Select(p => p.MyProperty)
                            .Distinct()
                            .ToList();

If your property is also a complex type you can create a custom comparer for the Distinct(), such as Distinct(OrderComparer), where OrderComparer could look like:

如果您的属性也是复杂类型,您可以为 Distinct() 创建自定义比较器,例如 Distinct(OrderComparer),其中 OrderComparer 可能如下所示:

public class OrderComparer : IEqualityComparer<Order>
{
    public bool Equals(Order o1, Order o2)
    {
        return o1.OrderID == o2.OrderID;
    }

    public int GetHashCode(Order obj)
    {
        return obj.OrderID.GetHashCode();
    }
}

回答by tymtam

There are many ways to skin a cat, but HashSet seems made for the task here.

有很多方法可以给猫剥皮,但 HashSet 似乎是为这里的任务而设计的。

var numbers = new[] { 0, 1, 2, 2, 2, 3, 4, 4, 5 };

HashSet<int> r = new HashSet<int>(numbers);

foreach( int i in r ) {
    Console.Write( "{0} ", i );
}

The output:

输出:

0 1 2 3 4 5

0 1 2 3 4 5