Hi there.. im new at c# and got some problems with my list an example

public List<Example> Test(int x)
var list = new List<Example>();
var data = (blabla linq to sql)
foreach(var item in data)
list.Add(new Example(...));

some of my data's are null and i need to remove null items from list. Any help ?

8 Years
Discussion Span
Last Post by Kekosavar
// option 1, use where clause to filter and AddRange to append non-null items to existing list
List<Example> list = new List<Example>();
list.AddRange(data.Where(item => item != null));

// option 2, use where clause to filter data and then convert to list
List<Example> list = data.Where(item => item != null).ToList();

// option 3, same as option 2, using query syntax
List<Example> list = (from item in data
                        where item != null
                        select item).ToList();

// option 4, query syntax version with explicit creation of new Example objects
List<Example> list = (from item in data
                        where item != null
                        select new Example
                            Foo = item.Foo,
                            Bar = item.Bar

// option 5, nulls already in list
list.RemoveAll(item => item == null);

Edited by apegram: n/a

Votes + Comments
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.