query an IList type object using Any element

2.9k Views Asked by At

Why the code below returns nothing when I try to query an IList type object?

IList<Person> personRecord = new List<Person>
    {
        new Person{ Name = "Samuel"},
        new Person{ Name = "Kenny Sammy"},
        new Person{ Name = "Jame Sam Lee"}
    };

var names = from b in personRecord
            where personRecord.Any(d => d.Name == "Sam")
            select b;

return names.ToList();
3

There are 3 best solutions below

0
On

Don't use Any simply use the condition in Where clause like:

var names = from b in personRecord 
            where b.Name ==  "Sam"
            select b;

or with a method syntax:

var names = personRecod.Where(b=> b.Name == "Sam");

If you are looking to match partial contents then use Contains like:

var names = personRecod.Where(b=> b.Name.Contains("Sam"));

To compare partial content with ignoring case use IndexOf like:

var names = personRecod.Where(b=> b.Name.IndexOf("Same", StringComparison.InvariantCultureIgnoreCase) > -1);
0
On

.Any returns a boolean, true/false, for whether any item in that collection satisfies your condition. If you changed your var names to the type you expected to receive (string) then you'd receive an error highlighting this.

As has been stated, what you are looking for is just the .Where method, or possibly a .FirstOrDefault or .First.

0
On

If you are just looking for the third item (as it's the only one having a name containing the complete word 'Sam') then:

var names = personRecord
    .Where(p => p.Name.Split(new char[] {' '}).Contains("Sam"));