Search code examples
c#winformslinqdatatabledatacolumn

how to find a string which is exist or not in some specific datacolumns of the datatable using LINQ query in C#?


I'm trying to find a string which is exist in some specified column of datatable or not. for example the DataTable contains 5 DataColumns. I want to find the string which is exist in any of the DataColumn1 or DataColumn2. I tried the below code part to get the single column1 values.

IEnumerable<string> query = from dr in dt.AsEnumerable()
                        select dr.Field<string>("ID");

How can I get the values of 2 or more columns?


Solution

  • You can return anonymouse type:

     var query = from dr in dt.AsEnumerable()
        select new {ID = dr.Field<string>("ID"), Column2 = dr.Field<string>("Column2")};
    

    And than you can use fields of that type:

    var Column2 = query.First().Column2;
    var ID = query.First().ID;