Baxter
Baxter

Reputation: 5845

Create new list from a old list using a lambda function

I have the following: List<InputRow> which contains a number of InputRow objects.

I am wondering if there is a way for me to use a lambda function on my original list to give me a new List where InputRow.someProperty > 1 for all the objects.

This would leave me with a list of InputRow objects all having someProperty greater than 1.

Upvotes: 3

Views: 2112

Answers (4)

Phil
Phil

Reputation: 43001

You can of course also do this:

var list = new List<string>(){ "a", "b", "c" };

list.RemoveAll(s => s == "b");

which removes the items in place instead of creating a new list.

Upvotes: 7

Smur
Smur

Reputation: 3113

Sure. You can do this:

var newList = inputRowList.Where(inputRow => inputRow.someProperty > 1).ToList();

Upvotes: 3

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48550

List<InputRow> newlist = oldlist.Where(x => x.someProperty > 1).ToList();

This will search your old list on the condition that someProperty > 1 and convert the result into List using .ToList()

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039130

You could use LINQ (a conjunction of the .Where() and .ToList() extension methods):

List<InputRow> originalList = ...
List<InputRow> filteredList = originalList
    .Where(x => x.someProperty > 1)
    .ToList();

Upvotes: 6

Related Questions