LINQ in C# - Examples - Set Operators (Distinct, Union, Intersect)

  • The set operators are used to perform mathematical set-type operations on sequences.

Distinct - Example

string[] PersonNames = { "Adams", "Arthur", "Buchanan", "Bush", "Carter", "Cleveland",
"Roosevelt","Coolidge", "Eisenhower", "Fillmore", "Ford", "Garfield",
"Grant", "Harding","Harrison", "Hayes", "Hoover", "Jackson", "Jefferson", "Johnson", "Kennedy","Lincoln", "Madison", "McKinley", "Monroe", "Nixon", "Fillmore", "Pierce", "Polk","Reagan", "Roosevelt", "Fillmore", "Taylor", "Truman", "Tyler", "Van Buren", "Washington",
                                    "Wilson" };


            Console.WriteLine($"No of Persons with Duplicates: {PersonNames.Count()}");

            string[] NoDuplicates = PersonNames.Distinct().ToArray();

            Console.WriteLine($"No of Persons with out Duplicate: {NoDuplicates.Count()}");
//Output
No of Persons with Duplicates: 38
No of Persons with out Duplicate: 35

Union- Example

  • Union and Concat do the same, But if there is duplicate entry Union will remove it and Concat will not remove duplicate elements.
 string[] ItemsSet1 = { "Item1", "Item2", "Item3"};
            string[] ItemsSet2 = { "Item1", "Item4", "Item5" };

            IEnumerable<string> Concatenated = ItemsSet1.Concat(ItemsSet2);
            IEnumerable<string> Unioned = ItemsSet1.Union(ItemsSet2);

            Console.WriteLine($"No of Item After Concat: {Concatenated.Count()}");
            Console.WriteLine($"No of Item After Union: {Unioned.Count()}");
//Output
No of Item After Concat: 6
No of Item After Union: 5

Intersect- Example

string[] ItemsSet1 = { "Item1", "Item2", "Item3"};
            string[] ItemsSet2 = { "Item1", "Item4", "Item5" };
          
            IEnumerable<string> CommonItems = ItemsSet1.Intersect(ItemsSet2);

            Console.WriteLine($"No of Common Item Between these sets: {CommonItems.Count()}");
            foreach (var item in CommonItems)
                Console.WriteLine(item);
//Output
No of Common Item Between these sets: 1
Item1

Except- Example 

  • Minus off the second sequence elements from the first sequence
string[] ItemsSet1 = { "Item1", "Item2", "Item3"};
            string[] ItemsSet2 = { "Item1", "Item4", "Item5" };
          
            IEnumerable<string> AfterMinusing = ItemsSet1.Except(ItemsSet2);

            Console.WriteLine($"Item sets1 -(minus) Items sets2: {AfterMinusing.Count()}");
            foreach (var item in AfterMinusing)
                Console.WriteLine(item)
//Output
Item sets1 -(minus) Items sets2: 2
Item2
Item3

No comments:

Post a Comment

Framework Fundamentals - String - Comparing Strings

In comparing two values, the .NET Framework differentiates the concepts of equality comparison and order comparison . Equality compariso...