I have a list with 2 columns and trying to use contains to search partially. Emp contains id and name.
var list = new List<Emp>();
list = list.Any(o => o.Contains(new Emp{ Name = name }));
However it is throwing an error: cannot convert from Emp to system.Linq. Iqueryable
any input on this will be helpful
Thanks in advance
It's not clear what exactly you're trying to do. You might want:
list = list.Where(emp => emp.Name == name).ToList();
or perhaps
list = list.Where(emp => emp.Name.Contains(name)).ToList();
It's not at all clear why you'd be trying to use Any
though.
EDIT: Given the comment, I suspect you really want:
list = list.Where(emp => emp.Name.StartsWith(name)).ToList();
(You might need to make it case-insensitive though.)
Or if you need to check each part of the name, you could either use a regular expression or:
list = list.Where(emp => emp.Name.Split(' ')
.Any(x => x.StartsWith(name))).ToList();
This last approach will be really inefficient though, as it will split each name each time you look through it... you could potentially make your Emp
objects immutable and cache the split form. Or look into a regular expression version. Either way, you probably don't just want string.Contains
as that will find matches anywhere in the name.
See more on this question at Stackoverflow