如何获得列表中的唯一记录

时间:2012-10-08 11:33:47

标签: c# list

我有一个包含货币的字符串列表,例如大小为1000.我想列出1000条记录中所有唯一货币的字符串。

现在就像 -

INR
USD
JPY
USD
USD
INR

我想要像 -

这样的字符串列表
INR
USD
JPY

只有唯一记录

最好不使用Linq

5 个答案:

答案 0 :(得分:4)

编辑:

我错过了部分“最好不使用LINQ”, 如果您使用的是.Net framework 2.0,或者您不想使用LINQ,则可以尝试以下操作。

List<string> list = new List<string> { "abc", "abc", "ab", "def", "abc", "def" };
list.Sort();
int i = 0;
while (i < list.Count - 1)
{
    if (list[i] == list[i + 1])
        list.RemoveAt(i);
    else
        i++;
}

使用Distinct()

List<string> list = new List<string> { "abc", "abc", "ab", "def", "abc","def" };
List<string> uniqueList = list.Distinct().ToList();

uniqueList将包含3个项"abc","ab","def"

请务必在顶部添加:using System.Linq;

答案 1 :(得分:1)

HashSet<T>正是您正在寻找的。参考MSDN

  

HashSet<T>类提供高性能的集合操作。集合是不包含重复元素的集合,其元素没有特定的顺序。

请注意,如果项目已添加到集合中,则HashSet<T>.Add(T item) method会返回bool - true; false如果该项目已经存在。

如果使用.NET 3.5或更高版本,

HashSet将适用于您,而不涉及Linq。

var hash = new HashSet<string>();
var collectionWithDup = new [] {"one","one","two","one","two","zero"}; 

foreach (var str in collectionWithDup)
{
    hash.Add(str);
}

// Here hash (of type HashSet) will be containing the unique list

如果您不使用.NET 3.5,请使用以下代码:

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

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

答案 2 :(得分:0)

为什么不将它们存储在HashSet中,然后从中读出来。该集合仅包含唯一值。

答案 3 :(得分:0)

假设您将这些值存储在数组或ArrayList中,有两种方法:

第一种方式

var UniqueValues = nonUnique.Distinct().ToArray();

第二种方式

//create a test arraylist of integers
int[] arr = {1, 2, 3, 3, 3, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 9};
ArrayList arrList = new ArrayList(arr);
//use a hashtable to create a unique list
Hashtable ht = new Hashtable();
foreach (int item in arrList) {
//set a key in the hashtable for our arraylist value - leaving the hashtable value      empty
    ht.Item[item] = null;
}
//now grab the keys from that hashtable into another arraylist
ArrayList distincArray = new ArrayList(ht.Keys);

答案 4 :(得分:0)

您可以创建自己的Distinct扩展方法:

public static class ExtensionMethods
{
  public static IEnumerable<T> Distinct<T>(this IEnumerable<T> list)
  {
    var distinctList = new List<T>();

    foreach (var item in list)
    {
      if (!distinctList.Contains(item)) distinctList.Add(item);
    }

    return distinctList;
  }
}

现在你可以这样做:

static void Main(string[] args)
{
  var list = new List<string>() {"INR", "USD", "JPY", "USD", "USD", "INR"};
  var distinctList = list.Distinct();
  foreach(var item in distinctList) Console.WriteLine(item);
}

将产生:

INR
USD
JPY
相关问题