如何从C#中收集得到独特的价值? [英] How to get unique values from a collection in C#?

查看:117
本文介绍了如何从C#中收集得到独特的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是用C#+ VSTS2008 + .NET 3.0。我有一个输入一个字符串数组。我需要输出数组的唯一的字符串。任何想法如何有效地实现这一点?

I am using C# + VSTS2008 + .Net 3.0. I have an input as a string array. And I need to output the unique strings of the array. Any ideas how to implement this efficiently?

例如,我有输入{ABC,ABCD,ABCD},我想成为输出{ABC,ABCD}。

For example, I have input {"abc", "abcd", "abcd"}, the output I want to be is {"abc", "abcd"}.

推荐答案

使用LINQ:

var uniquevalues = list.Distinct();

这是给你一个的IEnumerable<字符串>

如果你想要一个数组:

string[] uniquevalues = list.Distinct().ToArray();



如果您不使用.NET 3.5,这是一个有点复杂:

If you are not using .NET 3.5, it's a little more complicated:

List<string> newList = new List<string>();

foreach (string s in list)
{
   if (!newList.Contains(s))
      newList.Add(s);
}

// newList contains the unique values

另一种解决方案(也许有点快):

Another solution (maybe a little faster):

Dictionary<string,bool> dic = new Dictionary<string,bool>();

foreach (string s in list)
{
   dic[s] = true;
}

List<string> newList = new List<string>(dic.Keys);

// newList contains the unique values

这篇关于如何从C#中收集得到独特的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆