LINQ query to filter list by object property with multiple checks

I have a List of objects; I want to filter this list by the first letter in a string property of the objects.

public class MyObject
{
   public string Name { get; set; }
   public MyObject(){}
}

I am using a LINQ query:

List<MyObject> myList = FillList();

myList = myList.Where(p => p.Name[0] != "A").ToList();

My problem is that the first letter of Name may be preceded by whitespace. Three examples of Name property:

0 1 2 3 4
N A M E
  N A M E
    N A M

Rather than removing all whitespace from Name, can this be done with LINQ?

Upvotes: 2

Views: 2992

Answers (3)

a p
a p

Reputation: 3208

Sure you can! Use multiple checks in your .Where() clause, a la

p.Name[0] != 'A' && p.Name[1] != 'A'... 

Or, more simply, use string.Trim() to remove the trails G spaces:

.Where(p => p.Name.ToString().Trim().StartsWith('A')) `

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460380

You can use TrimStart, note that strings are immutable so you won't modify the original string.

myList = myList
    .Where(p => !p.Name.TrimStart().StartsWith("A")).ToList();

I'm using StartsWith because it's clear and also handles the case of an empty string.

Upvotes: 4

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101742

You can use TrimStart and temporarily remove whitespaces in the begining of your Name and check for the first letter

myList = myList.Where(p => p.Name.TrimStart(' ')[0] != 'A').ToList();

By the way you need to use 'A' becasue Name[0] is a char not a string.

Upvotes: 4

Related Questions