Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Any() argument versus parameter data type issues

Tags:

c#

linq

I have an object with a string-typed parameter called 'baan_cat_fam_code'. The code below is my attempt to find all items in the query that have a baan_cat_fam_code that exist in a generic string list called catFamCd.

query = query.Where(r => r.baan_cat_family_code.Any(s => catFamCode.Contains(s)));

The problem is that this won't compile - I get an error that states

"Argument type 'char' is not assignable to parameter type 'string'"

for some reason the predicate s is typed as char. So I append .ToString() to the argument in the .Contains method. However, when the code runs, I get the following exception thrown when the result of the query is bound to a listbox.

"The argument 'value' was the wrong type. Expected 'System.Char'. Actual 'System.String'."

This has got me scratching my head. Any assistance would be greatly appreciated.

Thanks!

like image 671
Andy Evans Avatar asked Jul 28 '11 15:07

Andy Evans


1 Answers

The problem you're running into is that baan_cat_family_code is of type string which implements IEnumerable<char>. When you call Any it's essentially saying

  • Is the predicate true for any char in this string

What you really want to be asking though is

  • Is this string in the list catFamCode

Try the following which does the latter

query = query.Where(r => catFamCode.Contains(r.baan_cat_family_code));
like image 180
JaredPar Avatar answered Nov 15 '22 08:11

JaredPar