Last active
August 29, 2015 13:57
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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