Reputation: 46222
I have the following query:
DataTable dtble = dt.AsEnumerable()
.Any(row => row.Field<String>("Course") == "Math")
.CopyToDataTable();
I would like the records to be filtered where Course
contains "Math"
. I tried to use .Any()
but it did not work.
To clarify, if Course has 12XMath123 I should still return a record as it contains "Math". Usig the Where cause will only return records where it is "Math" and not where it Contains "Math"
Upvotes: 1
Views: 58
Reputation: 33809
Try with Where()
instead of Any()
. This works for me:
DataTable dtble = dt.AsEnumerable()
.Where(row => row.Field<String>("Course") == "Math")
.CopyToDataTable();
As per comment, you could try StartsWith()
or EndsWith()
or Contains()
. Ex:
DataTable dtble = dt.AsEnumerable()
.Where(row => row.Field<String>("Course").Contains("Math"))
.CopyToDataTable();
Upvotes: 3
Reputation: 1531
You want to use Where rather than Any, and when comparing strings with Linq, you are better suited to use the .Equals method. You should also Trim() whitespace and use .Lower or .Upper to get consistent casing.
DataTable dtble = dt.AsEnumerable()
.Where(row => row.Field<string>("Course")
.Trim().Lower().Equals("math")
.CopyToDataTable();
Upvotes: 0
Reputation: 4594
Look here for basic Linq examples. But you're looking for Where, which returns a group of values that match the given predicate. Any returns a bool indicating whether any elements match a given predicate.
var dtble = dt.AsEnumerable()
.Where(row => row.Field<string>("Course") == "Math")
.CopyToDataTable();
Upvotes: 1