2010-08-10 55 views
1

在此帖子中Other Post我使用List<KeyValuePair<string, string>> IdentityLines = new List<KeyValuePair<string, string>>();的程序员建议来收集目录中某些文件中的多个字符串值。我现在想要从该列表中删除重复值。任何想法如何在C#中做到这一点?谢谢搜索并删除列表中的重复项

+0

参见http://stackoverflow.com/questions/47752/remove-duplicates-from-a-listt-in- c – 2010-08-10 20:55:45

回答

2
static List<T> RemoveDuplicates<T>(List<T> inputList) 
{ 
    Dictionary<T, int> uniqueStore = new Dictionary<T, int>(); 
    List<T> finalList = new List<T>(); 

    foreach (string currValue in inputList) 
    { 
     if (!uniqueStore.ContainsKey(currValue)) 
     { 
      uniqueStore.Add(currValue, 0); 
      finalList.Add(currValue); 
     } 
    } 
    return finalList; 
} 

http://www.kirupa.com/net/removingDuplicates.htm

如果你想返回一个IEnumerable而是改变你的返回类型IEnumerable<T>yieldreturn currValue,而不是将它添加到最后名单。

+0

在该链接上发布此行后列表 result = removeDuplicates(input);如果我想要写入文本文件,foreach循环会是什么样子?这是我的猜测,但我得到一个错误上的foreach声明不能类型字符串转换为System.Collections.Generic.List 的foreach(名单线结果) { 的StreamWriter FS = File.AppendText(@“C:\日志\“+”UserSummary“+”.log“); fs.Write(lines.Value +“\ r \ n”); fs.Close(); } – Josh 2010-08-10 21:02:38

+0

我想你想'foreach(结果中的字符串s)',根据你提供的错误。 – 2010-08-10 21:05:07

+0

嗨罗伯特 - 如果我这样做,那么我怎么写s的价值? s没有s.value,我可以在fs.Write()中使用; – Josh 2010-08-10 21:07:37

5

使用与Linq一起发现的Distinct方法。这里是一个使用int列表的例子。

Using System.Linq;

List<int> list = new List<int> { 1, 2, 3, 1, 3, 5 }; 
List<int> distinctList = list.Distinct().ToList(); 
0

我知道这样一个老问题,但在这里就是我如何做到这一点:

var inputKeys = new List<KeyValuePair<string, string>> 
          { 
           new KeyValuePair<string, string>("myFirstKey", "one"), 
           new KeyValuePair<string, string>("myFirstKey", "two"), 
           new KeyValuePair<string, string>("mySecondKey", "one"), 
           new KeyValuePair<string, string>("mySecondKey", "two"), 
           new KeyValuePair<string, string>("mySecondKey", "two"), 
          }; 
var uniqueKeys = new List<KeyValuePair<string, string>>(); 

//get rid of any duplicates 
uniqueKeys.AddRange(inputKeys.Where(keyPair => !uniqueKeys.Contains(keyPair))); 

Assert.AreEqual(inputKeys.Count(), 5); 
Assert.AreEqual(uniqueKeys.Count(), 4);