I have 2 data tables in C# Say dt1 and dt2. I need to fetch records from dt1 which are not present in dt2 on the basis of a Reference Id and need to select multiple columns via LINQ.
2 Answers
You can try this:
var result = dt1.AsEnumerable()
.Where(p => !dt2.AsEnumerable().Any(p2 => p2["id"] == p["id"]))
.CopyToDataTable();
You have plenty of options. You can also try the LINQ EXCEPT.
4 Comments
Mrinal Kamboj
Linq API are extension methods to IEnumerable<T>, it cannot be applied to the DataTable directly, use AsEnumerable for DataTable to call Linq APIsGerald Gonzales
@MrinalKamboj - Thank you, I forgot that part. I updated my answer.
Mrinal Kamboj
Even now its incorrect, since DataTable's
AsEnumerable yields IEnumerable<DataRow>, not the type T as expected. You need DataRow[<ColumnName>] to fetch a value.Mrinal Kamboj
This shall, though the complexity would be O(N^2), +1 for the effort and modification to produce correct result
You need to modify the DataRowComparer as per requirement, as I am currently only comparing Primary Key (replace with actual column name), check for reference, how to do it using multiple columns
C# Errors when doing a simple datarow comparer
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();
}
}
inline codeto highlight random terms.