-1

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.

4
  • 1
    Can you show the code that you tried already? Commented Sep 19, 2016 at 10:25
  • @MrinalKamboj you shouldn't have approved that edit. Don't use inline code to highlight random terms. Commented Sep 19, 2016 at 10:43
  • @CodeCaster Sure thanks, but I improved upon the Edit Commented Sep 19, 2016 at 10:44
  • var results = (from DataRow dr1 in dt1.AsEnumerable() where !(from DataRow dr2 in dt2.AsEnumerable() select cao["dr2"]).Contains(cs["OID"]) select new { col1 = cs["RefId"], col2 = cs["Id"]}); I have used this code but need something faster than this. Commented Sep 19, 2016 at 11:58

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Linq API are extension methods to IEnumerable<T>, it cannot be applied to the DataTable directly, use AsEnumerable for DataTable to call Linq APIs
@MrinalKamboj - Thank you, I forgot that part. I updated my answer.
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.
This shall, though the complexity would be O(N^2), +1 for the effort and modification to produce correct result
1

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(); 

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.