Bo5ku
Bo5ku

Reputation: 115

Query rows that the datatable field contain any item in the list<string>

i'm new in LINQ.
I wanna query all rows that the description column string (example value "i am feeling lucky today.") contains/match any item in a List<string> lst.
Example the list items contain {"lucky", "bad", "ok" }.
I would like to achieve by using linq only, but I am confuse are below methods correct??
thanks.

Option 1:
var item =
from a in datatbl.AsEnumerable()
from b in lst
where a.Field<string>("description").contains(b)
select a;

Option 2:
var item =
from a in datatbl.AsEnumerable()
where lst.Any(x=> a.Field<string>("description").Contains(x))
select a;

Upvotes: 3

Views: 21496

Answers (2)

Bo5ku
Bo5ku

Reputation: 115

Found out that if one row value is I'm not feeling Lucky, bad or ok today. with Linq below:

List<string> lst = new List<string>(new string[] { "Lucky", "bad", "ok" });
var item =  from a in datatbl.AsEnumerable()
            from b in lst
            where a.Field<string>("description").ToUpper().Contains(b.ToUpper())
            select a;

the result will return me 3 duplicated records of the same row, seem like it's not distinct by default. is this the case of above linq??

To get the distinct rows, i need to revise to:

List<string> lst = new List<string>(new string[] { "Lucky", "bad", "ok" });
var item =  (from a in datatbl.AsEnumerable()
            from b in lst
            where a.Field<string>("description").ToUpper().Contains(b.ToUpper())
            select a).Distinct();

Upvotes: 1

Les
Les

Reputation: 10605

Both of your options should work (change contains to Contains). But if you want to be case-insensitive, you will need to use a ToUpper or something.

For example, this code provides a "test jig" and handles case insensitivity.

        DataTable datatbl = new DataTable();
        datatbl.Columns.Add(new DataColumn("description",typeof(string)));
        // add simple test rows
        datatbl.Rows.Add("I'm feeling lucky today.");
        datatbl.Rows.Add("I'm feeling bad today.");
        datatbl.Rows.Add("I'm feeling good today.");
        // more test rows here...
        List<string> lst = new List<string>(new string[] { "Lucky", "bad", "ok" });

        var item =
            from a in datatbl.AsEnumerable()
            from b in lst
            where a.Field<string>("description").ToUpper().Contains(b.ToUpper())
            select a;

        var item2 =
            from a in datatbl.AsEnumerable()
            where lst.Any(x => a.Field<string>("description").ToUpper().Contains(x.ToUpper()))
            select a;

Upvotes: 6

Related Questions