Skip to content

Instantly share code, notes, and snippets.

@justinAurand
Last active August 29, 2015 13:57
Show Gist options
  • Save justinAurand/9842975 to your computer and use it in GitHub Desktop.
Save justinAurand/9842975 to your computer and use it in GitHub Desktop.
Demonstrating LINQ query with 1) check for null list, 2) check for null list items, and 3) check for null property before querying on it.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
var people = new List<Person>
{
new Person { Name = "Justin", Occupation = "Software Engineer" },
null,
new Person { Name = "Anthony", Occupation = "Software Developer" },
new Person { Name = "Daniel", Occupation = null },
new Person { Name = "Matthew", Occupation = "Lead Engineer" }
};
List<Engineer> engineers = (people == null) ? null :
people.Where(p => (p != null)
&& !string.IsNullOrWhiteSpace(p.Occupation)
&& p.Occupation.Contains("Engineer"))
.Select(p => new Engineer { Name = p.Name })
.ToList();
foreach (Engineer engineer in engineers)
Console.WriteLine(engineer.Name);
Console.ReadKey();
}
private class Person
{
internal string Name { get; set; }
internal string Occupation { get; set; }
}
private class Engineer
{
internal string Name { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment