Using Contains within Where for a list

c# dynamic-linq entity-framework-core linq sql

Question

So I am trying to retrieve results from a collection based on a property. I wanna get any results that hold that value within the list.

This is my code

I have tried with dynamic linq. It's not working

This is dynamic linq. Not working

var list = new List<string>(2) { "11111", "22222" };


accounts = accounts.Where("@0.Contains(outerIt.PartnerCompanyId)", list);

This is not working as well

accounts = accounts .Where(a =>
               a.PartnerCompanyId.Contains(list.Any().ToString()));

Also I want the SQL to generate something like this

WHERE PartnerCompanyId IN (@gp1, @gp2, @gp3, …)

I have been getting this even there are more than 1 value in the list. I want the same number of elements in the list in the parameters.

…WHERE PartnerCompanyId IN (@gp1)

Is thre any way to accomplish this?

1
0
7/18/2019 5:35:47 PM

Popular Answer

If I have understood your question correctly, you have a list of accounts and you want to check whether the accounts contain 'list[0] OR list[1] OR list[2] ...'.

I have managed to get a similar implementation working using Dynamic Linq.

Using your code as a base, here is what I did to get the query to work:

List<string> list = new List<string>(2) { "11111", "22222" };

string argumentString = "";

for (int i = 0; i < list.Length; i++)
{
    argumentString = argumentString + "@" + i;
    argumentString = argumentString + ".Contains(outerIt.PartnerCompanyId)";

    if (i != (list.Length - 1))
    {
        argumentString = argumentString + " or ";
    }
}

var accounts = accounts.Where(argumentString, list.ToArray());

The loop will create the string: "@0.Contains(outerIt.PartnerCompanyId) or @1.Contains(outerIt.PartnerCompanyId)"

Once this string is created all you need is a simple Linq query to check all of the items in the list.

Note: you can refer to arguments in order via and array but not a list. As shown here https://stackoverflow.com/a/40885380/10253157.

I hope this helps, I had a similar project and it took me quite a while to figure it out.

1
7/19/2019 1:14:36 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow