Apqu
Apqu

Reputation: 5031

c# list linq expression for 'x' equal to anything from another list?

I have a list of selected values and I want to see if my dataset contains any of these selected values, I know this can be done with linq but I am unsure how? This is what I have tried (the second line being where i am stuck)?

 List<ListItem> li = cbList.Items.Cast<ListItem>().Where(i => i.Selected).ToList();
 List<DataRow> dr = ds.Tables[0].Rows.Cast<DataRow>().Any(r => r["id"].ToString() == **ANY_OF_LI.SELECTEDVALUE**).ToList();

Upvotes: 0

Views: 856

Answers (2)

Habib
Habib

Reputation: 223187

You need:

List<DataRow> dr = ds.Tables[0].Rows.Cast<DataRow>()
                    .Where(r => li.Select(listItem => listItem.Value)
                        .Contains(r["id"].ToString()))
                    .ToList();

Instead of Any, use Where and Select the value from list of selected items and use Enumerable.Contains.

Just a minor suggestion, If any value of r["id"] is null then you could end up with a NRE, so use:

.Contains(Convert.ToString(r["id"]))))

Convert.ToString will return an empty string in case of null value.

Upvotes: 2

Dutts
Dutts

Reputation: 6191

Assuming r["id"].ToString() is what you're looking for in li, you could use Contains

List<DataRow> dr = ds.Tables[0].Rows.Cast<DataRow>().Any(r => li.Contains(r["id"].ToString()).ToList();

Upvotes: 0

Related Questions