C# 如何使用linq删除重复记录?

C# 如何使用linq删除重复记录?,c#,linq,c#-4.0,C#,Linq,C# 4.0,我有一个列表,想从列表中删除重复项。 数据以列表格式存储,例如IEnumerable tableData 如果我们将其视为表值, 父列表用于行,子列表用于每个列的值。 现在我想删除所有重复的行。下表中的值A重复 List<List<string>> ls = new List<List<string>>(); ls.Add(new List<string>() { "1", "A" }); ls.Add(new List<stri

我有一个列表,想从列表中删除重复项。 数据以列表格式存储,例如IEnumerable tableData 如果我们将其视为表值, 父列表用于行,子列表用于每个列的值。 现在我想删除所有重复的行。下表中的值A重复

List<List<string>> ls = new List<List<string>>();
ls.Add(new List<string>() { "1", "A" });
ls.Add(new List<string>() { "2", "B" });
ls.Add(new List<string>() { "3", "C" });
ls.Add(new List<string>() { "4", "A" });
ls.Add(new List<string>() { "5", "A" });
ls.Add(new List<string>() { "6", "D" });
IEnumerable<IEnumerable<string>> tableData = ls;

var abc = tableData.SelectMany(p => p).Distinct();   ///not work
操作后,我想abc应该是准确的tableData格式

这将展平列表并选择不同的字符串集


这将展平列表并选择不同的字符串集。

您可以使用下面的代码

         List<List<string>> ls=new List<List<string>>();
         ls.Add(new List<string>(){"Hello"});
         ls.Add(new List<string>(){"Hello"});
         ls.Add(new List<string>() { "He" });
         IEnumerable<IEnumerable<string>> tableData = ls;
         var abc = tableData.SelectMany(p => p).Distinct();
O/p为

你好


您可以使用下面的代码

         List<List<string>> ls=new List<List<string>>();
         ls.Add(new List<string>(){"Hello"});
         ls.Add(new List<string>(){"Hello"});
         ls.Add(new List<string>() { "He" });
         IEnumerable<IEnumerable<string>> tableData = ls;
         var abc = tableData.SelectMany(p => p).Distinct();
O/p为

你好


您可以使用传入的重载,假设您实际有一个IEnumerable

例如:

var items = tableData.SelectMany(x => x).Distinct(new TableComparer());
和比较器:

public class TableComparer : IEqualityComparer<PropertyData>
{
    public bool Equals(PropertyData x, PropertyData y)
    {
        return x.id == y.id;
    }

    public int GetHashCode(PropertyData pData)
    {
        return pData.id.GetHashCode();
    }
}

尽管你的问题不够清晰,但你可以使用传递一个IEnumerable的重载,假设你确实有一个IEnumerable

tableData.GroupBy(q => q.Skip(1).First()).Select(q => q.First())
例如:

var items = tableData.SelectMany(x => x).Distinct(new TableComparer());
和比较器:

public class TableComparer : IEqualityComparer<PropertyData>
{
    public bool Equals(PropertyData x, PropertyData y)
    {
        return x.id == y.id;
    }

    public int GetHashCode(PropertyData pData)
    {
        return pData.id.GetHashCode();
    }
}

虽然您的问题不够清晰。

什么是PropertyData?如果你能展示一个简短但完整的程序来演示你的数据是什么样子,那将非常有帮助。IEnumerable tableData包含完整的table。其中每个父列表作为行,每个子列表作为该行的列。@jon,我已经更改了类。@Ehsan,是的,它的列表。老实说,你还不清楚你有什么。一个简短但完整的例子会更清楚。什么是PropertyData?如果你能展示一个简短但完整的程序来演示你的数据是什么样子,那将非常有帮助。IEnumerable tableData包含完整的table。其中每个父列表作为行,每个子列表作为该行的列。@jon,我已经更改了类。@Ehsan,是的,它的列表。老实说,你还不清楚你有什么。一个简短但完整的例子会更清楚。var abc=tableData.Selectq=>q.ElementAt1.Distinct;不,也不是这样。不,它不起作用。它不会给出不同的记录。var abc=tableData.Selectq=>q.ElementAt1.distinct;不,也不是这样。不,它不起作用。它不会给出明确的记录。
tableData.GroupBy(q => q.Skip(1).First()).Select(q => q.First())