TheQuestioner
TheQuestioner

Reputation: 722

Filter a certain value in List according to Where using LINQ

assuming i have a list like below:

List <Customclass> someList = new List<CustomClass>() 
{
    new CustomClass { color = "Red", type = "lcd" },
    new CustomClass { color = "Red", type = "cvr" },
    new CustomClass { color = "Green", type = "lcd" },
    new Customclass { color = "Green", type = "cvr" },
    new CustomClass { color = "Blue", type = "lcd" },
    new CustomClass { color = "Blue", type = "cvr" }
};

how to can i filter the list to only show the color value and that the type must be lcd

something like this in SQL

SELECT [color] FROM [someList] WHERE [type] = 'lcd';

and the output would be:

Red
Green
Blue

i am very new to LINQ as i have no hint on how to do this thing. so i hope someone or anyone can help me here. thank you

Upvotes: 1

Views: 40

Answers (2)

Christos
Christos

Reputation: 53958

You need something like the following:

var colors = someList.Where(cc=>cc.type=="lcd")
                     .Select(cc=>cc.color);
  • Initially, you have to filter your list, using the Where method and a predicate that requires that the items in the output sequence should have as a type lcd.
  • Having filter your list, you have to make a projection using the Select method and pick only the color of each item of the filtered sequence.

Upvotes: 3

Zein Makki
Zein Makki

Reputation: 30022

Simple,

someList.Where(x=> x.type == "lcd").Select(x=> x.color).ToList();

Or

var results = (from x in someList
              where x.color == "lcd"
              select x.color).ToList();

Upvotes: 0

Related Questions