从List <string> </string>中获取唯一元素

时间:2012-03-01 08:56:09

标签: c# winforms list

我想从List中删除重复的元素。列表中的一些元素如下所示:

Book  23
Book  22
Book  19
Notebook 23
Notebook 22
Notebook 19
Pen 23
Pen 22
Pen 19

我想保留在列表中

Book 23
Notebook 23
Pen 23

我该怎么做?

3 个答案:

答案 0 :(得分:2)

基本循环怎么样?

List<string> nodup = dup.Distinct().ToList();
List<int> remIndex = new List<int>();
for (int nIdx = 0; nIdx < nodup.Count; nIdx++)
{
    string[] strArr = nodup[nIdx].Split(' ');
    if (String.Compare(strArr[1], "23", true) != 0)
        remIndex.Add(nIdx);
}
foreach (int remIdx in remIndex)
    nodup.RemoveAt(remIdx);

希望这有一些帮助...

答案 1 :(得分:1)

试试这个

  List<Person> distinctPeople = allPeople
  .GroupBy(p => p.PersonId)
  .Select(g => g.First())
  .ToList();

from this discussion

使用您的专栏名称

答案 2 :(得分:0)

试试这个

list.Sort();

Int32 index = 0; while (index < list.Count - 1) {
if (list[index] == list[index +1])
list.RemoveAt(index); else index++; }