Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>With the .NET 3.0 requirement, the Intersect LINQ extension method is not available, but you can provide your own extension method.</p> <p>All <em>you</em> need is the <code>MatchingRows</code> extension method (see below in the demo code) and then do:</p> <pre><code> IEnumerable&lt;DataRow&gt; unchangedZipCodes = dtExistingZipCodeInDB.MatchingRows(dtCSVExcelSource, "ZipCode"); </code></pre> <p>Then you can loop over unchangedZipCodes, which will contain only those rows with ZipCodes in common between dtExistingZipCodeInDB and dtCSVExcelSource.</p> <p>Below is demo code I wrote using LINQPad. I love <a href="http://www.linqpad.net/" rel="nofollow">LINQPad</a> -- it's great for proof of concept or scratchpadding/sandboxing some code quickly. But it is not <em>required</em> for the solution to this question. </p> <pre><code>void Main() { string colname = "ZipCode"; var dt = new DataTable(); dt.Columns.Add(colname, typeof(string)); dt.Rows.Add(new [] { "12345" } ); dt.Rows.Add(new [] { "67890" } ); dt.Rows.Add(new [] { "40291" } ); var dt2 = new DataTable(); dt2.Columns.Add(colname, typeof(string)); dt2.Rows.Add(new [] { "12345" } ); dt2.Rows.Add(new [] { "83791" } ); dt2.Rows.Add(new [] { "24520" } ); dt2.Rows.Add(new [] { "48023" } ); dt2.Rows.Add(new [] { "67890" } ); /// With .NET 3.5 LINQ extensions, it can be done inline. // var results = dt.AsEnumerable() // .Select(r =&gt; r.Field&lt;string&gt;(colname)) // .Intersect(dt2.AsEnumerable() // .Select(r =&gt; r.Field&lt;string&gt;(colname))); // Console.Write(String.Join(", ", results.ToArray())); var results = dt.MatchingRows(dt2, colname); foreach (DataRow r in results) Console.WriteLine(r[colname]); } public static class Extensions { /// With .NET 3.0 and no LINQ, create an extension method using yield. public static IEnumerable&lt;DataRow&gt; MatchingRows(this DataTable dt, DataTable dtCompare, string colName) { foreach (DataRow r in dt.Rows) { if (dtCompare.Select(String.Format("{0} = {1}", colName, r[(colName)])).Length &gt; 0) yield return r; } } } </code></pre> <p>Outputs:</p> <pre><code> 12345 67890 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload