954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Generic List Help

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 ?

Kekosavar
Newbie Poster
2 posts since Jun 2009
Reputation Points: 10
Solved Threads: 0
 
// 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);
apegram
LINQ!
Team Colleague
552 posts since Jan 2010
Reputation Points: 327
Solved Threads: 135
 

tyvm dude..

Kekosavar
Newbie Poster
2 posts since Jun 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You