简体   繁体   中英

How to add more than 1 condition when using LINQ-to-DataSet with Enumerable.Any() in C#?

I tried to check if values exist in dataTable.

With code:

bool lol = dtble.AsEnumerable().Any(l => array[0] == l.Field<String>("id"));

I need to add more condition to this code because I want to check more than one conditional.

My conditional need to add in this Linq is:

array[1] == l.Field<String>("Name")

and

array[2] == l.Field<String>("Stunt")

You can use the Logical AND ( && ) in LINQ to combine two conditions, Then your query will be like the following:

bool lol = dtble.AsEnumerable().Any(l =>
                                    array[0] == l.Field<String>("id") && 
                                    array[1] == l.Field<String>("Stunt"));

Now i got what you mean:

So you want to match the id, check if the name starts with same word in both array and DataTable and check for matching Stunt. So do the following:

bool lol = (from dRow in dtble.AsEnumerable()
            where array[0] == dRow.Field<string>("id")
            && GetFirstWord(array[1]) == GetFirstWord(dRow.Field<string>("Name"))
            && array[2] == dRow.Field<string>("Stunt")
            select dRow).Any(); 

And add this method:

// returns the first word in a string
private static string GetFirstWord(string str)
{
    return str.Split(' ').FirstOrDefault();
}

Edit:

You may need to replace this line :

&& GetFirstWord(array[1]) == GetFirstWord(dRow.Field<string>("Name")) 

If the fixed name is the one in the dataTable (as the first word) and the name might not be the first word in the array, then use this:

&& dRow.Field<string>("Name").Contains(GetFirstWord(array[1])) 
(LINQQUERY).AsEnumerable().Any(x => x.FieldName1 == (value) && x.FieldName2 == (value));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM