C# 在c中的数据表上应用Linq

C# 在c中的数据表上应用Linq,c#,linq,C#,Linq,我有两个C语言的数据表,比如dt1和dt2。我需要根据引用Id从dt1中获取dt2中不存在的记录,并且需要通过LINQ选择多个列。您可以尝试以下操作: var result = dt1.AsEnumerable() .Where(p => !dt2.AsEnumerable().Any(p2 => p2["id"] == p["id"])) .CopyToDataTable(); 你有很多选择。您也可以尝试。您需要根据需要修改Da

我有两个C语言的数据表,比如dt1和dt2。我需要根据引用Id从dt1中获取dt2中不存在的记录,并且需要通过LINQ选择多个列。

您可以尝试以下操作:

var result = dt1.AsEnumerable()
             .Where(p => !dt2.AsEnumerable().Any(p2 => p2["id"] == p["id"]))
             .CopyToDataTable();
你有很多选择。您也可以尝试。

您需要根据需要修改DataRowComparer,因为我目前只比较主键替换为实际列名,请检查参考,如何使用多个列来执行此操作


你能显示你已经尝试过的代码吗?@MrinalKamboj你不应该批准这个编辑。不要使用内联代码突出显示随机术语。@CodeCaster当然谢谢,但我改进了dt1.AsEnumerable where中来自DataRow dr1的Editvar results=!从dt2.AsEnumerable中的DataRow dr2中选择cao[dr2]。Containscs[OID]选择新的{col1=cs[RefId],col2=cs[Id]};我使用过这段代码,但需要比这更快的东西。Linq API是IEnumerable的扩展方法,它不能直接应用于DataTable,请使用AsEnumerable for DataTable调用LinqAPIs@MrinalKamboj-谢谢,我忘了那部分。我更新了我的答案。即使现在它仍然是不正确的,因为DataTable的AsEnumerable产生IEnumerable,而不是预期的T类型。您需要DataRow[]来获取一个值。尽管复杂度为^2,+1,但为了产生正确的结果所做的努力和修改都需要这样做
 var result = dt1.AsEnumerable().Except(dt2.AsEnumerable(), new  DataRowComparer()).CopyToDataTable();

public class DataRowComparer : IEqualityComparer<DataRow>
{
    /// <summary>
    /// Whether the two strings are equal
    /// </summary>
    public bool Equals(DataRow x, DataRow y)
    {
        return x["PrimaryKey"] == y["PrimaryKey"];
    }

    /// <summary>
    /// Return the hash code for this string.
    /// </summary>
    public int GetHashCode(DataRow dataRow)
    {
        return dataRow["PrimaryKey"].GetHashCode(); 

    }
}