如何删除具有重复属性的元组中的条目?

时间:2014-10-28 17:43:24

标签: linq c#-4.0 tuples

我有一个由三个属性组成的元组字典:名称,地址,电话。

示例:

  • Johnny Tarr,1234 Gaelic Way,555-402-9687
  • Patrick Murphy,1234 Taylor Road,555-555-5555
  • Patrick Murphy,1234 Morrison Court,555-555-5555

如何删除三个属性中有两个重复的条目?

尝试迭代集合失败:

for (int i = 0; i < fileList.Count - 1; i++)
{
    for (int j = i + 1; j < fileList.Count; j++)
    {
        // Test Results: There are supposed to be 362 duplicates. Outputting only 225 entries. A mix of duplicates and not duplicates.
        if (fileList[i].Item1.Equals(fileList[j].Item1, StringComparison.CurrentCultureIgnoreCase) && fileList[i].Item3.Equals(fileList[j].Item3, StringComparison.CurrentCultureIgnoreCase))
        {
            file.WriteLine(fileList[i].Item1 + "|" + fileList[i].Item2 + "|" + fileList[i].Item3);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

var distincts = fileList.GroupBy(t => t.Item1 + "," + t.Item3)
                        .Where(g => g.Count() == 1)
                        .Select(g => g.Single());

foreach (var item in distincts)
{
  Console.WriteLine(item);
}

这会按名称/电话对您的元组进行分组,然后只保留包含单个元组的组,然后为不同元组的输出列表选择单个元组。