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 ?

// 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
                        }).ToList();

// option 5, nulls already in list
list.RemoveAll(item => item == null);
commented: Nice +4

tyvm dude..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.