0

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

现在它就像 -

INR
USD
JPY
USD
USD
INR

我想要字符串列表 -

INR
USD
JPY

唯一的记录

最好不使用 Linq

4

5 回答 5

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;在顶部

于 2012-10-08T11:35:30.700 回答
1

HashSet<T>就是你要找的。参考MSDN

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

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

如果使用 .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);
}
于 2012-10-08T11:40:18.953 回答
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
于 2012-10-08T11:50:28.307 回答
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);
于 2012-10-08T11:42:42.293 回答
0

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

于 2012-10-08T11:35:56.033 回答