Find where row value is inside a list

64 views Asked by At
CompanyList companyList = new CompanyList();
companyList.matchCompanies();
CompanyListObject[] companyListObject = companyList.companyList;

List<double> companylist = new List<double>();
foreach (var company123 in companyListObject)
{
    if (company123.parentCompany == companyID)
    {
        companylist.Add(company123.companyID);
    }
}

IEnumerable<RaCallRatesMatched> items = 
    db.RaCallRatesMatched.Where(row => row.accountcode == companyIDDouble);

I want to pull the results where the Row Value is present in the list. Basically my list contains all the company IDs. It's quite a short list, some are 3-5 elements long. Rather than checking if the row is equal to just one of the list values. Can I check if it is equal to more of them?

Bear in mind that I can't use || statements in a fixed context as the list size will vary. For example compare with List[0] || List[1] || List[2] is too fixed and I'll get an exception if too long.

I can't make multiple calls to the database because each call is to a view that takes a very long time to build. Can I do this all in one call?

2

There are 2 answers

2
IAmGroot On

Use .Any()

e.g.

MyCompanyList.Any(x => x.Equals(MyCompanyName));

Where MyCompanyList is a List of Strings in this example. This can be applied to list of ints too. etc.

You can compare any parameter in complex classes, or any type of valid equality check.

More examples : http://www.dotnetperls.com/any

0
markthewizard1234 On
IEnumerable<RaCallRatesMatched> items = db.RaCallRatesMatched.Where(row => companylist.Any(y => y == row.accountcode));

This worked. Thanks Doomsknight and a couple of my work colleagues!