How do we find of two column values in another column using LINQ C#

BeUnique 2,332 Reputation points
2021-04-12T07:53:07.993+00:00

I have 3 columns and it contains some values.

I want to find of two column (COL1 and COL2) values in another column (COL3)

i.e. COL1 and COL2 values should check in COL3.

If any values found in in COL3, it should return true, else false.

     DataTable tblData = new DataTable();
     tblData.Columns.Add("COL1", typeof(string));
     tblData.Columns.Add("COL2", typeof(string));
     tblData.Columns.Add("COL3", typeof(string));
     tblData.Rows.Add("AM", "120", "AM-120");

Note : Here COL3 value may be either "AM-120" or "AM 120"

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. Viorel 126.1K Reputation points
    2021-04-12T08:17:16.24+00:00

    Try something like this:

    bool result = tblData.AsEnumerable( ).Any( r =>
     {
     string v1 = r.Field<string>( "COL1" );
     string v2 = r.Field<string>( "COL2" );
     string v3 = r.Field<string>( "COL3" );
    
     return v3.Contains( v1 ) || v3.Contains( v2 );
     } );
    

    Use "&&" instead of "||" if you need both values. It is also possible to perform case-insensitive comparison.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.