1.2. Using Set Semantics with Data
Problem
You would like to work with your collections using set operations for union, intersections, exceptions, and distinct items.
Solution
Use the Set operators provided as part of the Standard Query Operators to perform those operations.
- Distinct:
IEnumerable<string> whoLoggedIn = dailySecurityLog.Where(logEntry => logEntry.Contains("logged in")).Distinct( );- Union:
// Union Console.WriteLine("Employees for all projects"); var allProjectEmployees = project1.Union(project2.Union(project3));- Intersection:
// Intersect Console.WriteLine("Employees on every project"); var everyProjectEmployees = project1.Intersect(project2.Intersect(project3));- Exception:
Console.WriteLine("Employees on only one project"); var onlyProjectEmployees = allProjectEmployees.Except(unionIntersect);
Discussion
The Standard Query Operators are the set of methods that represent the LINQ pattern. This set includes operators to perform many different types of operations, such as filtering, projection, sorting, grouping, and many others, including set operations.
The set operations for the Standard Query Operators are:
Distinct
Union
Intersect
Except
The Distinct operator extracts all nonduplicate items from the collection or result set being worked with. Say, for example, that we had a set of strings representing login and logout behavior for a terminal services box for today:
// Distinct string[] dailySecurityLog = { "Bob logged in", "Bob logged out", "Bob logged in", "Bill logged in", ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access