From be01bb1c936cbd422c19a3f171aabecbac3d9986 Mon Sep 17 00:00:00 2001 From: DickBaker Date: Wed, 10 Jul 2024 09:17:00 +0100 Subject: [PATCH 1/8] give LINQ some C#12 love --- snippets/csharp/System.Linq/.editorconfig | 249 ++++++++ .../AggregateTSource/Enumerable.csproj | 7 + .../Enumerable/AggregateTSource/enumerable.cs | 564 ++++++++---------- .../Enumerable/Comparers/Comparers.csproj | 14 +- .../Enumerable/Comparers/CustomComparer.cs | 92 +-- .../Comparers/EncapsulatedComparer.cs | 63 +- .../Overview/IGrouping.csproj | 15 + .../Overview/Project.csproj | 8 - .../Overview/igrouping.cs | 10 +- .../ILookupTKey,TElement/Overview/ILookup.cs | 12 +- .../Overview/ILookup.csproj | 15 + .../Overview/Project.csproj | 8 - .../Overview/IOrderedEnumerable.cs | 12 +- .../Overview/IOrderedEnumerable.csproj | 15 + .../Overview/Project.csproj | 8 - snippets/csharp/System.Linq/Linq - Copy.txt | 61 ++ .../Overview/Project.csproj | 8 - .../AggregateTSource/AggregateTSource.csproj | 15 + .../Queryable/AggregateTSource/Project.csproj | 8 - .../Queryable/AggregateTSource/queryable.cs | 530 ++++++++-------- 20 files changed, 1010 insertions(+), 704 deletions(-) create mode 100644 snippets/csharp/System.Linq/.editorconfig create mode 100644 snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj delete mode 100644 snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/Project.csproj create mode 100644 snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj delete mode 100644 snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/Project.csproj create mode 100644 snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj delete mode 100644 snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/Project.csproj create mode 100644 snippets/csharp/System.Linq/Linq - Copy.txt delete mode 100644 snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Project.csproj create mode 100644 snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj delete mode 100644 snippets/csharp/System.Linq/Queryable/AggregateTSource/Project.csproj diff --git a/snippets/csharp/System.Linq/.editorconfig b/snippets/csharp/System.Linq/.editorconfig new file mode 100644 index 00000000000..336d6ecabe3 --- /dev/null +++ b/snippets/csharp/System.Linq/.editorconfig @@ -0,0 +1,249 @@ +# Remove the line below if you want to inherit .editorconfig settings from higher directories +root = true + +# C# files +[*.cs] + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_size = 4 +indent_style = space +tab_width = 4 + +# New line preferences +end_of_line = crlf +insert_final_newline = false + +#### .NET Coding Conventions #### + +# Organize usings +dotnet_separate_import_directive_groups = false +dotnet_sort_system_directives_first = true +file_header_template = unset + +# this. and Me. preferences +dotnet_style_qualification_for_event = false +dotnet_style_qualification_for_field = false +dotnet_style_qualification_for_method = false +dotnet_style_qualification_for_property = false + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true +dotnet_style_predefined_type_for_member_access = true + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary +dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary +dotnet_style_parentheses_in_other_operators = never_if_unnecessary +dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members + +# Expression-level preferences +dotnet_style_coalesce_expression = true +dotnet_style_collection_initializer = true +dotnet_style_explicit_tuple_names = true +dotnet_style_namespace_match_folder = true +dotnet_style_null_propagation = true +dotnet_style_object_initializer = true +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_prefer_auto_properties = true:warning +dotnet_style_prefer_collection_expression = when_types_loosely_match +dotnet_style_prefer_compound_assignment = true +dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = true:suggestion +dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed +dotnet_style_prefer_inferred_anonymous_type_member_names = true +dotnet_style_prefer_inferred_tuple_names = true +dotnet_style_prefer_is_null_check_over_reference_equality_method = true +dotnet_style_prefer_simplified_boolean_expressions = true +dotnet_style_prefer_simplified_interpolation = true + +# Field preferences +dotnet_style_readonly_field = true + +# Parameter preferences +dotnet_code_quality_unused_parameters = all + +# Suppression preferences +dotnet_remove_unnecessary_suppression_exclusions = none + +# New line preferences +dotnet_style_allow_multiple_blank_lines_experimental = false +dotnet_style_allow_statement_immediately_after_block_experimental = true + +#### C# Coding Conventions #### + +# var preferences +csharp_style_var_elsewhere = false:silent +csharp_style_var_for_built_in_types = true:silent +csharp_style_var_when_type_is_apparent = true:silent + +# Expression-bodied members +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_constructors = true:silent +csharp_style_expression_bodied_indexers = true +csharp_style_expression_bodied_lambdas = true:suggestion +csharp_style_expression_bodied_local_functions = true:suggestion +csharp_style_expression_bodied_methods = true:silent +csharp_style_expression_bodied_operators = true:silent +csharp_style_expression_bodied_properties = true:silent + +# Pattern matching preferences +csharp_style_pattern_matching_over_as_with_null_check = true +csharp_style_pattern_matching_over_is_with_cast_check = true +csharp_style_prefer_extended_property_pattern = true +csharp_style_prefer_not_pattern = true +csharp_style_prefer_pattern_matching = true +csharp_style_prefer_switch_expression = true + +# Null-checking preferences +csharp_style_conditional_delegate_call = true + +# Modifier preferences +csharp_prefer_static_anonymous_function = true +csharp_prefer_static_local_function = true +csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async +csharp_style_prefer_readonly_struct = true +csharp_style_prefer_readonly_struct_member = true + +# Code-block preferences +csharp_prefer_braces = true:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_style_namespace_declarations = file_scoped:silent +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_primary_constructors = true:suggestion +csharp_style_prefer_top_level_statements = true:silent + +# Expression-level preferences +csharp_prefer_simple_default_expression = true +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_prefer_index_operator = true +csharp_style_prefer_local_over_anonymous_function = true +csharp_style_prefer_null_check_over_type_check = true +csharp_style_prefer_range_operator = true +csharp_style_prefer_tuple_swap = true +csharp_style_prefer_utf8_string_literals = true +csharp_style_throw_expression = true +csharp_style_unused_value_assignment_preference = discard_variable:silent +csharp_style_unused_value_expression_statement_preference = discard_variable + +# 'using' directive preferences +csharp_using_directive_placement = outside_namespace:suggestion + +# New line preferences +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false:silent +csharp_style_allow_embedded_statements_on_same_line_experimental = true + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = true +csharp_new_line_before_else = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = all +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Wrapping preferences +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +[*.{cs,vb}] +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = crlf +dotnet_style_namespace_match_folder = true:suggestion +dotnet_style_predefined_type_for_member_access = true:silent +dotnet_style_require_accessibility_modifiers = omit_if_default:silent +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_property = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_event = false:silent +dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_other_operators = always_for_clarity:silent \ No newline at end of file diff --git a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj index a269962b552..ff1021b1134 100644 --- a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj +++ b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj @@ -5,4 +5,11 @@ net8.0 + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + diff --git a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs index 5b7949c4f0c..caa6c5709a6 100644 --- a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs +++ b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs @@ -4,19 +4,16 @@ namespace SequenceExamples { - class Program + static class Program { // This part is just for testing the examples - static void Main(string[] args) - { - OfTypeEx1(); - } + static void Main() => OfTypeEx1(); #region Aggregate static void AggregateEx1() { // - string sentence = "the quick brown fox jumps over the lazy dog"; + const string sentence = "the quick brown fox jumps over the lazy dog"; // Split the string into individual words. string[] words = sentence.Split(' '); @@ -36,7 +33,7 @@ static void AggregateEx1() static void AggregateEx2() { // - int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 }; + int[] ints = [4, 8, 8, 3, 9, 0, 7, 8, 2]; // Count the even numbers in the array, using a seed value of 0. int numEven = ints.Aggregate(0, (total, next) => @@ -52,7 +49,7 @@ static void AggregateEx2() static void AggregateEx3() { // - string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" }; + string[] fruits = ["apple", "mango", "orange", "passionfruit", "grape"]; // Determine whether any string in the array is longer than "banana". string longestName = @@ -86,14 +83,14 @@ class Pet public static void AllEx() { // Create an array of Pets. - Pet[] pets = { new Pet { Name="Barley", Age=10 }, + Pet[] pets = [ new Pet { Name="Barley", Age=10 }, new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=6 } }; + new Pet { Name="Whiskers", Age=6 } ]; // Determine whether all pet names // in the array start with 'B'. bool allStartWithB = pets.All(pet => - pet.Name.StartsWith("B")); + pet.Name.StartsWith('B')); Console.WriteLine( "{0} pet names start with 'B'.", @@ -122,19 +119,19 @@ class Person public static void AllEx2() { - List people = new List - { new Person { LastName = "Haas", - Pets = new Pet[] { new Pet { Name="Barley", Age=10 }, + List people = + [ new Person { LastName = "Haas", + Pets = [ new Pet { Name="Barley", Age=10 }, new Pet { Name="Boots", Age=14 }, - new Pet { Name="Whiskers", Age=6 }}}, + new Pet { Name="Whiskers", Age=6 }]}, new Person { LastName = "Fakhouri", - Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}}, + Pets = [new Pet { Name = "Snowball", Age = 1}]}, new Person { LastName = "Antebi", - Pets = new Pet[] { new Pet { Name = "Belle", Age = 8} }}, + Pets = [new Pet { Name = "Belle", Age = 8}]}, new Person { LastName = "Philips", - Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2}, - new Pet { Name = "Rover", Age = 13}} } - }; + Pets = [ new Pet { Name = "Sweetie", Age = 2}, + new Pet { Name = "Rover", Age = 13}] } + ]; // Determine which people have pets that are all older than 5. IEnumerable names = from person in people @@ -163,8 +160,8 @@ static class Any1 public static void AnyEx1() { // - List numbers = new List { 1, 2 }; - bool hasElements = numbers.Any(); + List numbers = [1, 2]; + bool hasElements = numbers.Count != 0; Console.WriteLine("The list {0} empty.", hasElements ? "is not" : "is"); @@ -189,23 +186,23 @@ class Person public static void AnyEx2() { - List people = new List - { new Person { LastName = "Haas", - Pets = new Pet[] { new Pet { Name="Barley", Age=10 }, + List people = + [ new Person { LastName = "Haas", + Pets = [ new Pet { Name="Barley", Age=10 }, new Pet { Name="Boots", Age=14 }, - new Pet { Name="Whiskers", Age=6 }}}, + new Pet { Name="Whiskers", Age=6 }]}, new Person { LastName = "Fakhouri", - Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}}, + Pets = [new Pet { Name = "Snowball", Age = 1}]}, new Person { LastName = "Antebi", - Pets = new Pet[] { }}, + Pets = []}, new Person { LastName = "Philips", - Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2}, - new Pet { Name = "Rover", Age = 13}} } - }; + Pets = [ new Pet { Name = "Sweetie", Age = 2}, + new Pet { Name = "Rover", Age = 13}] } + ]; // Determine which people have a non-empty Pet array. IEnumerable names = from person in people - where person.Pets.Any() + where person.Pets.Length != 0 select person.LastName; foreach (string name in names) @@ -237,13 +234,13 @@ public static void AnyEx3() { // Create an array of Pets. Pet[] pets = - { new Pet { Name="Barley", Age=8, Vaccinated=true }, + [ new Pet { Name="Barley", Age=8, Vaccinated=true }, new Pet { Name="Boots", Age=4, Vaccinated=false }, - new Pet { Name="Whiskers", Age=1, Vaccinated=false } }; + new Pet { Name="Whiskers", Age=1, Vaccinated=false } ]; // Determine whether any pets over age 1 are also unvaccinated. bool unvaccinated = - pets.Any(p => p.Age > 1 && p.Vaccinated == false); + pets.Any(p => p.Age > 1 && !p.Vaccinated); Console.WriteLine( "There {0} unvaccinated animals over age one.", @@ -275,13 +272,14 @@ static void AsEnumerableEx1() { // Create a new Clump object. Clump fruitClump = - new Clump { "apple", "passionfruit", "banana", + new() + { "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry" }; // First call to Where(): // Call Clump's Where() method with a predicate. IEnumerable query1 = - fruitClump.Where(fruit => fruit.Contains("o")); + fruitClump.Where(fruit => fruit.Contains('o')); Console.WriteLine("query1 has been created.\n"); @@ -289,7 +287,7 @@ static void AsEnumerableEx1() // First call AsEnumerable() to hide Clump's Where() method and thereby // force System.Linq.Enumerable's Where() method to be called. IEnumerable query2 = - fruitClump.AsEnumerable().Where(fruit => fruit.Contains("o")); + fruitClump.AsEnumerable().Where(fruit => fruit.Contains('o')); // Display the output. Console.WriteLine("query2 has been created."); @@ -308,7 +306,7 @@ static void AsEnumerableEx1() static void AverageEx1() { // - List grades = new List { 78, 92, 100, 37, 81 }; + List grades = [78, 92, 100, 37, 81]; double average = grades.Average(); @@ -323,7 +321,7 @@ static void AverageEx1() static void AverageEx2() { // - long?[] longs = { null, 10007L, 37L, 399846234235L }; + long?[] longs = [null, 10007L, 37L, 399846234235L]; double? average = longs.Average(); @@ -338,7 +336,7 @@ static void AverageEx2() static void AverageEx3() { // - string[] numbers = { "10007", "37", "299846234235" }; + string[] numbers = ["10007", "37", "299846234235"]; double average = numbers.Average(num => long.Parse(num)); @@ -353,7 +351,7 @@ static void AverageEx3() static void AverageEx4() { // - string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; + string[] fruits = ["apple", "banana", "mango", "orange", "passionfruit", "grape"]; double average = fruits.Average(s => s.Length); @@ -370,10 +368,7 @@ static void AverageEx4() static void CastEx1() { // - System.Collections.ArrayList fruits = new System.Collections.ArrayList(); - fruits.Add("mango"); - fruits.Add("apple"); - fruits.Add("lemon"); + System.Collections.ArrayList fruits = ["mango", "apple", "lemon"]; IEnumerable query = fruits.Cast().OrderBy(fruit => fruit).Select(fruit => fruit); @@ -408,17 +403,17 @@ class Pet static Pet[] GetCats() { - Pet[] cats = { new Pet { Name="Barley", Age=8 }, + Pet[] cats = [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + new Pet { Name="Whiskers", Age=1 } ]; return cats; } static Pet[] GetDogs() { - Pet[] dogs = { new Pet { Name="Bounder", Age=3 }, + Pet[] dogs = [ new Pet { Name="Bounder", Age=3 }, new Pet { Name="Snoopy", Age=14 }, - new Pet { Name="Fido", Age=9 } }; + new Pet { Name="Fido", Age=9 } ]; return dogs; } @@ -428,7 +423,8 @@ public static void ConcatEx1() Pet[] dogs = GetDogs(); IEnumerable query = - cats.Select(cat => cat.Name).Concat(dogs.Select(dog => dog.Name)); + cats.Select(cat => cat.Name) + .Concat(dogs.Select(dog => dog.Name)); foreach (string name in query) { @@ -478,9 +474,9 @@ public static void ConcatEx2() static void ContainsEx1() { // - string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; + string[] fruits = ["apple", "banana", "mango", "orange", "passionfruit", "grape"]; - string fruit = "mango"; + const string fruit = "mango"; bool hasMango = fruits.Contains(fruit); @@ -500,11 +496,11 @@ static void ContainsEx1() static void CountEx1() { // - string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; + string[] fruits = ["apple", "banana", "mango", "orange", "passionfruit", "grape"]; try { - int numberOfFruits = fruits.Count(); + int numberOfFruits = fruits.Length; Console.WriteLine( "There are {0} fruits in the collection.", numberOfFruits); @@ -532,13 +528,13 @@ class Pet public static void CountEx2() { - Pet[] pets = { new Pet { Name="Barley", Vaccinated=true }, + Pet[] pets = [ new Pet { Name="Barley", Vaccinated=true }, new Pet { Name="Boots", Vaccinated=false }, - new Pet { Name="Whiskers", Vaccinated=false } }; + new Pet { Name="Whiskers", Vaccinated=false } ]; try { - int numberUnvaccinated = pets.Count(p => p.Vaccinated == false); + int numberUnvaccinated = pets.Count(p => !p.Vaccinated); Console.WriteLine("There are {0} unvaccinated animals.", numberUnvaccinated); } catch (OverflowException) @@ -568,9 +564,9 @@ class Pet public static void DefaultIfEmptyEx1() { List pets = - new List{ new Pet { Name="Barley", Age=8 }, + [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + new Pet { Name="Whiskers", Age=1 } ]; foreach (Pet pet in pets.DefaultIfEmpty()) { @@ -591,7 +587,7 @@ public static void DefaultIfEmptyEx1() static void DefaultIfEmptyEx1a() { // - List numbers = new List(); + List numbers = []; foreach (int number in numbers.DefaultIfEmpty()) { @@ -617,19 +613,19 @@ class Pet public static void DefaultIfEmptyEx2() { - Pet defaultPet = new Pet { Name = "Default Pet", Age = 0 }; + Pet defaultPet = new() { Name = "Default Pet", Age = 0 }; List pets1 = - new List{ new Pet { Name="Barley", Age=8 }, + [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + new Pet { Name="Whiskers", Age=1 } ]; foreach (Pet pet in pets1.DefaultIfEmpty(defaultPet)) { Console.WriteLine("Name: {0}", pet.Name); } - List pets2 = new List(); + List pets2 = []; foreach (Pet pet in pets2.DefaultIfEmpty(defaultPet)) { @@ -654,7 +650,7 @@ public static void DefaultIfEmptyEx2() static void DistinctEx1() { // - List ages = new List { 21, 46, 46, 55, 17, 21, 55, 55 }; + List ages = [21, 46, 46, 55, 17, 21, 55, 55]; IEnumerable distinctAges = ages.Distinct(); @@ -683,12 +679,12 @@ static void ElementAtEx1() { // string[] names = - { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", + [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; - Random random = new Random(DateTime.Now.Millisecond); + "Hedlund, Magnus", "Ito, Shu" ]; + Random random = new(DateTime.Now.Millisecond); - string name = names.ElementAt(random.Next(0, names.Length)); + string name = names[random.Next(0, names.Length)]; Console.WriteLine("The name chosen at random is '{0}'.", name); @@ -706,17 +702,17 @@ static void ElementAtOrDefaultEx1() { // string[] names = - { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; + [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", + "Hedlund, Magnus", "Ito, Shu" ]; - int index = 20; + const int index = 20; string name = names.ElementAtOrDefault(index); Console.WriteLine( "The name chosen at index {0} is '{1}'.", index, - String.IsNullOrEmpty(name) ? "" : name); + string.IsNullOrEmpty(name) ? "" : name); /* This code produces the following output: @@ -731,27 +727,28 @@ The name chosen at index 20 is ''. static void EmptyEx1() { // - IEnumerable empty = Enumerable.Empty(); + IEnumerable empty = []; // } static void EmptyEx2() { // - string[] names1 = { "Hartono, Tommy" }; - string[] names2 = { "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; - string[] names3 = { "Solanki, Ajay", "Hoeing, Helge", + string[] names1 = ["Hartono, Tommy"]; + string[] names2 = [ "Adams, Terry", "Andersen, Henriette Thaulow", + "Hedlund, Magnus", "Ito, Shu" ]; + string[] names3 = [ "Solanki, Ajay", "Hoeing, Helge", "Andersen, Henriette Thaulow", - "Potra, Cristina", "Iallo, Lucio" }; + "Potra, Cristina", "Iallo, Lucio" ]; List namesList = - new List { names1, names2, names3 }; + [names1, names2, names3]; // Only include arrays that have four or more elements IEnumerable allNames = namesList.Aggregate(Enumerable.Empty(), - (current, next) => next.Length > 3 ? current.Union(next) : current); + (current, next) => + next.Length > 3 ? current.Union(next) : current); foreach (string name in allNames) { @@ -778,8 +775,8 @@ static void EmptyEx2() static void ExceptEx1() { // - double[] numbers1 = { 2.0, 2.0, 2.1, 2.2, 2.3, 2.3, 2.4, 2.5 }; - double[] numbers2 = { 2.2 }; + double[] numbers1 = [2.0, 2.0, 2.1, 2.2, 2.3, 2.3, 2.4, 2.5]; + double[] numbers2 = [2.2]; IEnumerable onlyInFirstSet = numbers1.Except(numbers2); @@ -803,10 +800,10 @@ static void ExceptEx1() static void FirstEx1() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 435, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 435, 67, 12, 19 ]; - int first = numbers.First(); + int first = numbers[0]; Console.WriteLine(first); @@ -821,8 +818,8 @@ static void FirstEx1() static void FirstEx2() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 435, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 435, 67, 12, 19 ]; int first = numbers.First(number => number > 80); @@ -841,7 +838,7 @@ static void FirstEx2() static void FirstOrDefaultEx1() { // - int[] numbers = { }; + int[] numbers = []; int first = numbers.FirstOrDefault(); Console.WriteLine(first); @@ -856,9 +853,9 @@ static void FirstOrDefaultEx1() static void FirstOrDefaultEx2() { // - string[] names = { "Hartono, Tommy", "Adams, Terry", + string[] names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; + "Hedlund, Magnus", "Ito, Shu" ]; string firstLongName = names.FirstOrDefault(name => name.Length > 20); @@ -882,7 +879,7 @@ There is not a name longer than 30 characters. static void FirstOrDefaultEx3() { // - List months = new List { }; + List months = []; // Setting the default value to 1 after the query. int firstMonth1 = months.FirstOrDefault(); @@ -921,10 +918,10 @@ public static void GroupByEx1() { // Create a list of pets. List pets = - new List{ new Pet { Name="Barley", Age=8 }, + [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 }, - new Pet { Name="Daisy", Age=4 } }; + new Pet { Name="Daisy", Age=4 } ]; // Group the pets using Age as the key value // and selecting only the pet's Name for each value. @@ -961,10 +958,10 @@ public static void GroupByEx2() { // Create a list of pets. List pets = - new List{ new Pet { Name="Barley", Age=8 }, + [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 }, - new Pet { Name="Daisy", Age=4 } }; + new Pet { Name="Daisy", Age=4 } ]; // Group the pets using Age as the key value // and selecting only the pet's Name for each value. @@ -1000,10 +997,10 @@ public static void GroupByEx3() { // Create a list of pets. List petsList = - new List{ new Pet { Name="Barley", Age=8.3 }, + [ new Pet { Name="Barley", Age=8.3 }, new Pet { Name="Boots", Age=4.9 }, new Pet { Name="Whiskers", Age=1.5 }, - new Pet { Name="Daisy", Age=4.3 } }; + new Pet { Name="Daisy", Age=4.3 } ]; // Group Pet objects by the Math.Floor of their age. // Then project an anonymous type from each group @@ -1063,10 +1060,10 @@ public static void GroupByEx4() { // Create a list of pets. List petsList = - new List{ new Pet { Name="Barley", Age=8.3 }, + [ new Pet { Name="Barley", Age=8.3 }, new Pet { Name="Boots", Age=4.9 }, new Pet { Name="Whiskers", Age=1.5 }, - new Pet { Name="Daisy", Age=4.3 } }; + new Pet { Name="Daisy", Age=4.3 } ]; // Group Pet.Age values by the Math.Floor of the age. // Then project an anonymous type from each group @@ -1131,17 +1128,17 @@ class Pet public static void GroupJoinEx1() { - Person magnus = new Person { Name = "Hedlund, Magnus" }; - Person terry = new Person { Name = "Adams, Terry" }; - Person charlotte = new Person { Name = "Weiss, Charlotte" }; + Person magnus = new() { Name = "Hedlund, Magnus" }; + Person terry = new() { Name = "Adams, Terry" }; + Person charlotte = new() { Name = "Weiss, Charlotte" }; - Pet barley = new Pet { Name = "Barley", Owner = terry }; - Pet boots = new Pet { Name = "Boots", Owner = terry }; - Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; + Pet barley = new() { Name = "Barley", Owner = terry }; + Pet boots = new() { Name = "Boots", Owner = terry }; + Pet whiskers = new() { Name = "Whiskers", Owner = charlotte }; + Pet daisy = new() { Name = "Daisy", Owner = magnus }; - List people = new List { magnus, terry, charlotte }; - List pets = new List { barley, boots, whiskers, daisy }; + List people = [magnus, terry, charlotte]; + List pets = [barley, boots, whiskers, daisy]; // Create a list where each element is an anonymous // type that contains a person's name and @@ -1185,17 +1182,17 @@ public static void GroupJoinEx1() // Uses query syntax. public static void GroupJoinEx2() { - Person magnus = new Person { Name = "Hedlund, Magnus" }; - Person terry = new Person { Name = "Adams, Terry" }; - Person charlotte = new Person { Name = "Weiss, Charlotte" }; + Person magnus = new() { Name = "Hedlund, Magnus" }; + Person terry = new() { Name = "Adams, Terry" }; + Person charlotte = new() { Name = "Weiss, Charlotte" }; - Pet barley = new Pet { Name = "Barley", Owner = terry }; - Pet boots = new Pet { Name = "Boots", Owner = terry }; - Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; + Pet barley = new() { Name = "Barley", Owner = terry }; + Pet boots = new() { Name = "Boots", Owner = terry }; + Pet whiskers = new() { Name = "Whiskers", Owner = charlotte }; + Pet daisy = new() { Name = "Daisy", Owner = magnus }; - List people = new List { magnus, terry, charlotte }; - List pets = new List { barley, boots, whiskers, daisy }; + List people = [magnus, terry, charlotte]; + List pets = [barley, boots, whiskers, daisy]; // var query = from person in people @@ -1226,8 +1223,8 @@ on person equals pet.Owner into petCollection static void IntersectEx1() { // - int[] id1 = { 44, 26, 92, 30, 71, 38 }; - int[] id2 = { 39, 59, 83, 47, 26, 4, 30 }; + int[] id1 = [44, 26, 92, 30, 71, 38]; + int[] id2 = [39, 59, 83, 47, 26, 4, 30]; IEnumerable both = id1.Intersect(id2); @@ -1261,17 +1258,17 @@ class Pet public static void JoinEx1() { - Person magnus = new Person { Name = "Hedlund, Magnus" }; - Person terry = new Person { Name = "Adams, Terry" }; - Person charlotte = new Person { Name = "Weiss, Charlotte" }; + Person magnus = new() { Name = "Hedlund, Magnus" }; + Person terry = new() { Name = "Adams, Terry" }; + Person charlotte = new() { Name = "Weiss, Charlotte" }; - Pet barley = new Pet { Name = "Barley", Owner = terry }; - Pet boots = new Pet { Name = "Boots", Owner = terry }; - Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; + Pet barley = new() { Name = "Barley", Owner = terry }; + Pet boots = new() { Name = "Boots", Owner = terry }; + Pet whiskers = new() { Name = "Whiskers", Owner = charlotte }; + Pet daisy = new() { Name = "Daisy", Owner = magnus }; - List people = new List { magnus, terry, charlotte }; - List pets = new List { barley, boots, whiskers, daisy }; + List people = [magnus, terry, charlotte]; + List pets = [barley, boots, whiskers, daisy]; // Create a list of Person-Pet pairs where // each element is an anonymous type that contains a @@ -1308,10 +1305,10 @@ public static void JoinEx1() static void LastEx1() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 67, 12, 19 ]; - int last = numbers.Last(); + int last = numbers[^1]; Console.WriteLine(last); @@ -1326,8 +1323,8 @@ static void LastEx1() static void LastEx2() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 67, 12, 19 ]; int last = numbers.Last(num => num > 80); @@ -1346,10 +1343,10 @@ static void LastEx2() static void LastOrDefaultEx1() { // - string[] fruits = { }; + string[] fruits = []; string last = fruits.LastOrDefault(); Console.WriteLine( - String.IsNullOrEmpty(last) ? "" : last); + string.IsNullOrEmpty(last) ? "" : last); /* This code produces the following output: @@ -1362,7 +1359,7 @@ static void LastOrDefaultEx1() static void LastOrDefaultEx2() { // - double[] numbers = { 49.6, 52.3, 51.0, 49.4, 50.2, 48.3 }; + double[] numbers = [49.6, 52.3, 51.0, 49.4, 50.2, 48.3]; double last50 = numbers.LastOrDefault(n => Math.Round(n) == 50.0); @@ -1386,7 +1383,7 @@ The last number that rounds to 40 is . static void LastOrDefaultEx3() { // - List daysOfMonth = new List { }; + List daysOfMonth = []; // Setting the default value to 1 after the query. int lastDay1 = daysOfMonth.LastOrDefault(); @@ -1414,10 +1411,10 @@ The value of the lastDay2 variable is 1 public static void LongCountEx1() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; - long count = fruits.LongCount(); + long count = fruits.Length; Console.WriteLine("There are {0} fruits in the collection.", count); @@ -1440,9 +1437,9 @@ class Pet public static void LongCountEx2() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, + Pet[] pets = [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + new Pet { Name="Whiskers", Age=1 } ]; const int Age = 3; @@ -1464,7 +1461,7 @@ There are 2 animals over age 3. static void MaxEx1() { // - List longs = new List { 4294967296L, 466855135L, 81125L }; + List longs = [4294967296L, 466855135L, 81125L]; long max = longs.Max(); @@ -1481,7 +1478,7 @@ The largest number is 4294967296. static void MaxEx2() { // - double?[] doubles = { null, 1.5E+104, 9E+103, -2E+103 }; + double?[] doubles = [null, 1.5E+104, 9E+103, -2E+103]; double? max = doubles.Max(); @@ -1518,7 +1515,7 @@ class Pet : IComparable int IComparable.CompareTo(Pet other) { int sumOther = other.Age + other.Name.Length; - int sumThis = this.Age + this.Name.Length; + int sumThis = Age + Name.Length; if (sumOther > sumThis) return -1; @@ -1531,9 +1528,9 @@ int IComparable.CompareTo(Pet other) public static void MaxEx3() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, + Pet[] pets = [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + new Pet { Name="Whiskers", Age=1 } ]; Pet max = pets.Max(); @@ -1561,9 +1558,9 @@ class Pet public static void MaxEx4() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, + Pet[] pets = [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + new Pet { Name="Whiskers", Age=1 } ]; int max = pets.Max(pet => pet.Age + pet.Name.Length); @@ -1586,7 +1583,7 @@ The maximum pet age plus name length is 14. static void MinEx1() { // - double[] doubles = { 1.5E+104, 9E+103, -2E+103 }; + double[] doubles = [1.5E+104, 9E+103, -2E+103]; double min = doubles.Min(); @@ -1603,7 +1600,7 @@ The smallest number is -2E+103. static void MinEx2() { // - int?[] grades = { 78, 92, null, 99, 37, 81 }; + int?[] grades = [78, 92, null, 99, 37, 81]; int? min = grades.Min(); @@ -1638,9 +1635,9 @@ class Pet : IComparable /// 1 if this Pet's age is greater. int IComparable.CompareTo(Pet other) { - if (other.Age > this.Age) + if (other.Age > Age) return -1; - else if (other.Age == this.Age) + else if (other.Age == Age) return 0; else return 1; @@ -1649,9 +1646,9 @@ int IComparable.CompareTo(Pet other) public static void MinEx3() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, + Pet[] pets = [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + new Pet { Name="Whiskers", Age=1 } ]; Pet min = pets.Min(); @@ -1679,9 +1676,9 @@ class Pet public static void MinEx4() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, + Pet[] pets = [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + new Pet { Name="Whiskers", Age=1 } ]; int min = pets.Min(pet => pet.Age); @@ -1701,15 +1698,15 @@ The youngest animal is age 1. static void OfTypeEx1() { // - System.Collections.ArrayList fruits = new() - { + System.Collections.ArrayList fruits = + [ "Mango", "Orange", null, "Apple", 3.0, "Banana" - }; + ]; // Apply OfType() to the ArrayList. IEnumerable query1 = fruits.OfType(); @@ -1760,9 +1757,9 @@ class Pet public static void OrderByEx1() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, + Pet[] pets = [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + new Pet { Name="Whiskers", Age=1 } ]; IEnumerable query = pets.OrderBy(pet => pet.Age); @@ -1783,52 +1780,30 @@ public static void OrderByEx1() } // - public class CaseInsensitiveCompare : IComparer - { - // Define a compare method that ignores case. - public int Compare(string s1, string s2) - { - return string.Compare(s1, s2, true); - } - } - - public class CaseSensitiveCompare : IComparer - { - // Define a compare method that does not ignore case. - public int Compare(string s1, string s2) - { - return string.Compare(s1, s2, false); - } - } - public static void OrderByIComparer() { - - string[] unsortedArray = { "one", "Four", "One", "First", "four", "first" }; + string[] unsortedArray = ["one", "Four", "One", "First", "four", "first"]; // Sort the array, ignoring case, and display the results. - var sortedArray = unsortedArray.OrderBy(a => a, new CaseInsensitiveCompare()); - Console.WriteLine("Case-insensitive sort of the strings " + - "in the array:"); - foreach (var element in sortedArray) + IOrderedEnumerable sortedArray = unsortedArray.OrderBy(a => a, StringComparer.OrdinalIgnoreCase); + Console.WriteLine("Case-insensitive sort of the strings in the array:"); + foreach (string element in sortedArray) { Console.WriteLine(element); } // Sort the array, not ignoring case, and display the results. - sortedArray = unsortedArray.OrderBy(a => a, new CaseSensitiveCompare()); - Console.WriteLine("\nCase-sensitive sort of the strings in " + - "the array:"); - foreach (var element in sortedArray) + sortedArray = unsortedArray.OrderBy(a => a, StringComparer.Ordinal); + Console.WriteLine("\nCase-sensitive sort of the strings in the array:"); + foreach (string element in sortedArray) { Console.WriteLine(element); } // Change the lambda expression to sort by the length of each string. - sortedArray = unsortedArray.OrderBy(a => (a.Length).ToString(), new CaseInsensitiveCompare()); - Console.WriteLine("\nSort based on the lengths of the strings in " + - "the array:"); - foreach (var element in sortedArray) + sortedArray = unsortedArray.OrderBy(a => (a.Length).ToString(), StringComparer.OrdinalIgnoreCase); + Console.WriteLine("\nSort based on the lengths of the strings in the array:"); + foreach (string element in sortedArray) { Console.WriteLine(element); } @@ -1905,7 +1880,7 @@ public int Compare(decimal d1, decimal d2) } if (fractional1 == fractional2) - return Decimal.Compare(d1, d2); + return decimal.Compare(d1, d2); else if (fractional1 > fractional2) return 1; else @@ -1916,7 +1891,7 @@ public int Compare(decimal d1, decimal d2) public static void OrderByDescendingEx1() { List decimals = - new List { 6.2m, 8.3m, 0.5m, 1.3m, 6.3m, 9.7m }; + [6.2m, 8.3m, 0.5m, 1.3m, 6.3m, 9.7m]; IEnumerable query = decimals.OrderByDescending(num => @@ -1980,7 +1955,7 @@ static void RepeatEx1() IEnumerable strings = Enumerable.Repeat("I like programming.", 15); - foreach (String str in strings) + foreach (string str in strings) { Console.WriteLine(str); } @@ -2012,7 +1987,7 @@ I like programming. static void ReverseEx1() { // - char[] apple = { 'a', 'p', 'p', 'l', 'e' }; + char[] apple = ['a', 'p', 'p', 'l', 'e']; char[] reversed = apple.Reverse().ToArray(); @@ -2062,8 +2037,8 @@ static void SelectEx1() static void SelectEx2() { // - string[] fruits = { "apple", "banana", "mango", "orange", - "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", "orange", + "passionfruit", "grape" ]; var query = fruits.Select((fruit, index) => @@ -2095,18 +2070,18 @@ static class SelectMany1 class PetOwner { public string Name { get; set; } - public List Pets { get; set; } + public List Pets { get; set; } } public static void SelectManyEx1() { PetOwner[] petOwners = - { new PetOwner { Name="Higa, Sidney", - Pets = new List{ "Scruffy", "Sam" } }, + [ new PetOwner { Name="Higa, Sidney", + Pets = ["Scruffy", "Sam"] }, new PetOwner { Name="Ashkenazi, Ronen", - Pets = new List{ "Walker", "Sugar" } }, + Pets = ["Walker", "Sugar"] }, new PetOwner { Name="Price, Vernette", - Pets = new List{ "Scratches", "Diesel" } } }; + Pets = ["Scratches", "Diesel"] } ]; // Query using SelectMany(). IEnumerable query1 = petOwners.SelectMany(petOwner => petOwner.Pets); @@ -2123,7 +2098,7 @@ public static void SelectManyEx1() // This code shows how to use Select() // instead of SelectMany(). - IEnumerable> query2 = + IEnumerable> query2 = petOwners.Select(petOwner => petOwner.Pets); Console.WriteLine("\nUsing Select():"); @@ -2131,7 +2106,7 @@ public static void SelectManyEx1() // Notice that two foreach loops are required to // iterate through the results // because the query returns a collection of arrays. - foreach (List petList in query2) + foreach (List petList in query2) { foreach (string pet in petList) { @@ -2177,14 +2152,14 @@ class PetOwner public static void SelectManyEx2() { PetOwner[] petOwners = - { new PetOwner { Name="Higa, Sidney", - Pets = new List{ "Scruffy", "Sam" } }, + [ new PetOwner { Name="Higa, Sidney", + Pets = ["Scruffy", "Sam"] }, new PetOwner { Name="Ashkenazi, Ronen", - Pets = new List{ "Walker", "Sugar" } }, + Pets = ["Walker", "Sugar"] }, new PetOwner { Name="Price, Vernette", - Pets = new List{ "Scratches", "Diesel" } }, + Pets = ["Scratches", "Diesel"] }, new PetOwner { Name="Hines, Patrick", - Pets = new List{ "Dusty" } } }; + Pets = ["Dusty"] } ]; // Project the items in the array by appending the index // of each PetOwner to each pet's name in that petOwner's @@ -2223,26 +2198,27 @@ class PetOwner public static void SelectManyEx3() { PetOwner[] petOwners = - { new PetOwner { Name="Higa", - Pets = new List{ "Scruffy", "Sam" } }, + [ new PetOwner { Name="Higa", + Pets = ["Scruffy", "Sam"] }, new PetOwner { Name="Ashkenazi", - Pets = new List{ "Walker", "Sugar" } }, + Pets = ["Walker", "Sugar"] }, new PetOwner { Name="Price", - Pets = new List{ "Scratches", "Diesel" } }, + Pets = ["Scratches", "Diesel"] }, new PetOwner { Name="Hines", - Pets = new List{ "Dusty" } } }; + Pets = ["Dusty"] } ]; // Project the pet owner's name and the pet's name. var query = petOwners - .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName }) - .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S")) + .SelectMany(petOwner => petOwner.Pets, + (petOwner, petName) => new { petOwner, petName }) + .Where(ownerAndPet => ownerAndPet.petName.StartsWith('S')) .Select(ownerAndPet => - new - { - Owner = ownerAndPet.petOwner.Name, - Pet = ownerAndPet.petName - } + new + { + Owner = ownerAndPet.petOwner.Name, + Pet = ownerAndPet.petName + } ); // Print the results. @@ -2274,12 +2250,12 @@ class Pet public static void SequenceEqualEx1() { - Pet pet1 = new Pet { Name = "Turbo", Age = 2 }; - Pet pet2 = new Pet { Name = "Peanut", Age = 8 }; + Pet pet1 = new() { Name = "Turbo", Age = 2 }; + Pet pet2 = new() { Name = "Peanut", Age = 8 }; // Create two lists of pets. - List pets1 = new List { pet1, pet2 }; - List pets2 = new List { pet1, pet2 }; + List pets1 = [pet1, pet2]; + List pets2 = [pet1, pet2]; bool equal = pets1.SequenceEqual(pets2); @@ -2307,14 +2283,14 @@ class Pet public static void SequenceEqualEx2() { - Pet pet1 = new Pet() { Name = "Turbo", Age = 2 }; - Pet pet2 = new Pet() { Name = "Peanut", Age = 8 }; + Pet pet1 = new() { Name = "Turbo", Age = 2 }; + Pet pet2 = new() { Name = "Peanut", Age = 8 }; // Create two lists of pets. - List pets1 = new List { pet1, pet2 }; + List pets1 = [pet1, pet2]; List pets2 = - new List { new Pet { Name = "Turbo", Age = 2 }, - new Pet { Name = "Peanut", Age = 8 } }; + [ new Pet { Name = "Turbo", Age = 2 }, + new Pet { Name = "Peanut", Age = 8 } ]; bool equal = pets1.SequenceEqual(pets2); @@ -2334,7 +2310,7 @@ The lists are not equal. static void SingleEx1() { // - string[] fruits1 = { "orange" }; + string[] fruits1 = ["orange"]; string fruit1 = fruits1.Single(); @@ -2348,7 +2324,7 @@ static void SingleEx1() // // - string[] fruits2 = { "orange", "apple" }; + string[] fruits2 = ["orange", "apple"]; string fruit2 = null; try @@ -2376,8 +2352,8 @@ The collection does not contain exactly one element. static void SingleEx2() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; string fruit1 = fruits.Single(fruit => fruit.Length > 10); @@ -2417,7 +2393,7 @@ static void SingleEx2() static void SingleOrDefaultEx1() { // - string[] fruits1 = { "orange" }; + string[] fruits1 = ["orange"]; string fruit1 = fruits1.SingleOrDefault(); @@ -2431,12 +2407,12 @@ static void SingleOrDefaultEx1() // // - string[] fruits2 = { }; + string[] fruits2 = []; string fruit2 = fruits2.SingleOrDefault(); Console.WriteLine( - String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2); + string.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2); /* This code produces the following output: @@ -2449,8 +2425,8 @@ No such string! static void SingleOrDefaultEx2() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; string fruit1 = fruits.SingleOrDefault(fruit => fruit.Length > 10); @@ -2468,7 +2444,7 @@ static void SingleOrDefaultEx2() fruits.SingleOrDefault(fruit => fruit.Length > 15); Console.WriteLine( - String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2); + string.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2); /* This code produces the following output: @@ -2481,7 +2457,7 @@ No such string! static void SingleOrDefaultEx3() { // - int[] pageNumbers = { }; + int[] pageNumbers = []; // Setting the default value to 1 after the query. int pageNumber1 = pageNumbers.SingleOrDefault(); @@ -2509,7 +2485,7 @@ The value of the pageNumber2 variable is 1 static void SkipEx1() { // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; Console.WriteLine("All grades except the first three:"); foreach (int grade in grades.Skip(3)) @@ -2534,7 +2510,7 @@ static void SkipEx1() static void SkipWhileEx1() { // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; IEnumerable lowerGrades = grades @@ -2561,8 +2537,8 @@ static void SkipWhileEx1() static void SkipWhileEx2() { // - int[] amounts = { 5000, 2500, 9000, 8000, - 6500, 4000, 1500, 5500 }; + int[] amounts = [ 5000, 2500, 9000, 8000, + 6500, 4000, 1500, 5500 ]; IEnumerable query = amounts.SkipWhile((amount, index) => amount > index * 1000); @@ -2596,11 +2572,10 @@ class Package public static void SumEx1() { List packages = - new List - { new Package { Company = "Coho Vineyard", Weight = 25.2 }, + [ new Package { Company = "Coho Vineyard", Weight = 25.2 }, new Package { Company = "Lucerne Publishing", Weight = 18.7 }, new Package { Company = "Wingtip Toys", Weight = 6.0 }, - new Package { Company = "Adventure Works", Weight = 33.8 } }; + new Package { Company = "Adventure Works", Weight = 33.8 } ]; double totalWeight = packages.Sum(pkg => pkg.Weight); @@ -2618,7 +2593,7 @@ public static void SumEx1() static void SumEx2() { // - List numbers = new List { 43.68F, 1.25F, 583.7F, 6.5F }; + List numbers = [43.68F, 1.25F, 583.7F, 6.5F]; float sum = numbers.Sum(); @@ -2635,7 +2610,7 @@ The sum of the numbers is 635.13. static void SumEx3() { // - float?[] points = { null, 0, 92.83F, null, 100.0F, 37.46F, 81.1F }; + float?[] points = [null, 0, 92.83F, null, 100.0F, 37.46F, 81.1F]; float? sum = points.Sum(); @@ -2655,7 +2630,7 @@ static void SumEx3() static void TakeEx1() { // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; IEnumerable topThreeGrades = grades.OrderByDescending(grade => grade).Take(3); @@ -2681,11 +2656,11 @@ static void TakeEx1() static void TakeWhileEx1() { // - string[] fruits = { "apple", "banana", "mango", "orange", - "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", "orange", + "passionfruit", "grape" ]; IEnumerable query = - fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0); + fruits.TakeWhile(fruit => string.Compare("orange", fruit, true) != 0); foreach (string fruit in query) { @@ -2705,8 +2680,8 @@ static void TakeWhileEx1() static void TakeWhileEx2() { // - string[] fruits = { "apple", "passionfruit", "banana", "mango", - "orange", "blueberry", "grape", "strawberry" }; + string[] fruits = [ "apple", "passionfruit", "banana", "mango", + "orange", "blueberry", "grape", "strawberry" ]; IEnumerable query = fruits.TakeWhile((fruit, index) => fruit.Length >= index); @@ -2735,8 +2710,8 @@ static void TakeWhileEx2() static void ThenByEx1() { // - string[] fruits = { "grape", "passionfruit", "banana", "mango", - "orange", "raspberry", "apple", "blueberry" }; + string[] fruits = [ "grape", "passionfruit", "banana", "mango", + "orange", "raspberry", "apple", "blueberry" ]; // Sort the strings first by their length and then //alphabetically by passing the identity selector function. @@ -2769,24 +2744,16 @@ static void ThenByEx1() static class ThenByDescending { // - public class CaseInsensitiveComparer : IComparer - { - public int Compare(string x, string y) - { - return string.Compare(x, y, true); - } - } - public static void ThenByDescendingEx1() { - string[] fruits = { "apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE" }; + string[] fruits = ["apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE"]; // Sort the strings first ascending by their length and // then descending using a custom case insensitive comparer. IEnumerable query = fruits .OrderBy(fruit => fruit.Length) - .ThenByDescending(fruit => fruit, new CaseInsensitiveComparer()); + .ThenByDescending(fruit => fruit, StringComparer.OrdinalIgnoreCase); foreach (string fruit in query) { @@ -2823,11 +2790,10 @@ class Package public static void ToArrayEx1() { List packages = - new List - { new Package { Company = "Coho Vineyard", Weight = 25.2 }, + [ new Package { Company = "Coho Vineyard", Weight = 25.2 }, new Package { Company = "Lucerne Publishing", Weight = 18.7 }, new Package { Company = "Wingtip Toys", Weight = 6.0 }, - new Package { Company = "Adventure Works", Weight = 33.8 } }; + new Package { Company = "Adventure Works", Weight = 33.8 } ]; string[] companies = packages.Select(pkg => pkg.Company).ToArray(); @@ -2864,11 +2830,10 @@ class Package public static void ToDictionaryEx1() { List packages = - new List - { new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L }, + [ new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L }, new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L }, new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L }, - new Package { Company = "Adventure Works", Weight = 33.8, TrackingNumber = 4665518773L } }; + new Package { Company = "Adventure Works", Weight = 33.8, TrackingNumber = 4665518773L } ]; // Create a Dictionary of Package objects, // using TrackingNumber as the key. @@ -2901,8 +2866,8 @@ public static void ToDictionaryEx1() static void ToListEx1() { // - string[] fruits = { "apple", "passionfruit", "banana", "mango", - "orange", "blueberry", "grape", "strawberry" }; + string[] fruits = [ "apple", "passionfruit", "banana", "mango", + "orange", "blueberry", "grape", "strawberry" ]; List lengths = fruits.Select(fruit => fruit.Length).ToList(); @@ -2943,8 +2908,7 @@ public static void ToLookupEx1() { // Create a list of Packages. List packages = - new List - { new Package { Company = "Coho Vineyard", + [ new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L }, new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L }, @@ -2953,7 +2917,7 @@ public static void ToLookupEx1() new Package { Company = "Contoso Pharmaceuticals", Weight = 9.3, TrackingNumber = 670053128L }, new Package { Company = "Wide World Importers", - Weight = 33.8, TrackingNumber = 4665518773L } }; + Weight = 33.8, TrackingNumber = 4665518773L } ]; // Create a Lookup to organize the packages. // Use the first character of Company as the key value. @@ -2996,8 +2960,8 @@ Wide World Importers 4665518773 static void UnionEx1() { // - int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 }; - int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 }; + int[] ints1 = [5, 3, 9, 7, 5, 9, 3, 7]; + int[] ints2 = [8, 3, 6, 4, 4, 9, 1, 0]; IEnumerable union = ints1.Union(ints2); @@ -3022,8 +2986,8 @@ static void WhereEx1() { // List fruits = - new List { "apple", "passionfruit", "banana", "mango", - "orange", "blueberry", "grape", "strawberry" }; + [ "apple", "passionfruit", "banana", "mango", + "orange", "blueberry", "grape", "strawberry" ]; IEnumerable query = fruits.Where(fruit => fruit.Length < 6); @@ -3044,7 +3008,7 @@ static void WhereEx1() static void WhereEx2() { // - int[] numbers = { 0, 30, 20, 15, 90, 85, 40, 75 }; + int[] numbers = [0, 30, 20, 15, 90, 85, 40, 75]; IEnumerable query = numbers.Where((number, index) => number <= index * 10); @@ -3069,12 +3033,12 @@ static void WhereEx2() static void ZipEx() { // - int[] numbers = { 1, 2, 3, 4 }; - string[] words = { "one", "two", "three" }; + int[] numbers = [1, 2, 3, 4]; + string[] words = ["one", "two", "three"]; - var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second); + IEnumerable numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second); - foreach (var item in numbersAndWords) + foreach (string item in numbersAndWords) Console.WriteLine(item); // This code produces the following output: @@ -3091,10 +3055,10 @@ static void AppendEx() { // // Creating a list of numbers - List numbers = new List { 1, 2, 3, 4 }; + List numbers = [1, 2, 3, 4]; // Trying to append any value of the same type - numbers.Append(5); + _ = numbers.Append(5); // It doesn't work because the original list has not been changed Console.WriteLine(string.Join(", ", numbers)); @@ -3103,7 +3067,7 @@ static void AppendEx() Console.WriteLine(string.Join(", ", numbers.Append(5))); // If you prefer, you can create a new list explicitly - List newNumbers = numbers.Append(5).ToList(); + List newNumbers = [.. numbers, 5]; // And then write to the console output Console.WriteLine(string.Join(", ", newNumbers)); @@ -3122,10 +3086,10 @@ static void PrependEx() { // // Creating a list of numbers - List numbers = new List { 1, 2, 3, 4 }; + List numbers = [1, 2, 3, 4]; // Trying to prepend any value of the same type - numbers.Prepend(0); + _ = numbers.Prepend(0); // It doesn't work because the original list has not been changed Console.WriteLine(string.Join(", ", numbers)); @@ -3153,7 +3117,7 @@ static void SkipLast() { #if NETCOREAPP // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; IEnumerable topGrades = grades.OrderByDescending(g => g).SkipLast(3); @@ -3182,7 +3146,7 @@ static void TakeLast() { #if NETCOREAPP // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; IEnumerable bottomThreeGrades = grades.OrderByDescending(grade => grade).TakeLast(3); diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj b/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj index ce892295f4f..3248dce4c43 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj @@ -1,9 +1,17 @@ - + Exe - net6.0;net472 - Program + net8.0;net472 + Comparers.Program + latest + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs b/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs index 7f33762c739..b95ad6aa6d8 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs @@ -1,6 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; +using System.CodeDom; + +namespace Comparers; // public class Product @@ -15,16 +18,13 @@ class ProductComparer : IEqualityComparer // Products are equal if their names and product numbers are equal. public bool Equals(Product x, Product y) { - //Check whether the compared objects reference the same data. - if (Object.ReferenceEquals(x, y)) return true; - - //Check whether any of the compared objects is null. - if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) - return false; + if (ReferenceEquals(x, y)) return true; - //Check whether the products' properties are equal. - return x.Code == y.Code && x.Name == y.Name; + return x is not null && //Check if any of the compared objects is null + y is not null && + x.Code == y.Code && //Check if the products' properties are equal. + x.Name == y.Name; } // If Equals() returns true for a pair of objects @@ -33,13 +33,13 @@ public bool Equals(Product x, Product y) public int GetHashCode(Product product) { //Check whether the object is null - if (Object.ReferenceEquals(product, null)) return 0; + if (product is null) return 0; - //Get hash code for the Name field if it is not null. - int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode(); + //Get hash code for the Name field + var hashProductName = product.Name.GetHashCode(); - //Get hash code for the Code field. - int hashProductCode = product.Code.GetHashCode(); + //Get hash code for the Code field + var hashProductCode = product.Code.GetHashCode(); //Calculate the hash code for the product. return hashProductName ^ hashProductCode; @@ -47,16 +47,16 @@ public int GetHashCode(Product product) } // -class Program +static class Program { static void Main(string[] args) { // - Product[] store1 = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 } }; + Product[] store1 = [ new() { Name = "apple", Code = 9 }, + new() { Name = "orange", Code = 4 } ]; - Product[] store2 = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "lemon", Code = 12 } }; + Product[] store2 = [ new() { Name = "apple", Code = 9 }, + new() { Name = "lemon", Code = 12 } ]; // Get the products from the first array // that have duplicates in the second array. @@ -64,7 +64,7 @@ static void Main(string[] args) IEnumerable duplicates = store1.Intersect(store2, new ProductComparer()); - foreach (var product in duplicates) + foreach (Product product in duplicates) Console.WriteLine(product.Name + " " + product.Code); /* @@ -74,11 +74,11 @@ apple 9 // // - Product[] store10 = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 } }; + Product[] store10 = [ new() { Name = "apple", Code = 9 }, + new() { Name = "orange", Code = 4 } ]; - Product[] store20 = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "lemon", Code = 12 } }; + Product[] store20 = [ new() { Name = "apple", Code = 9 }, + new() { Name = "lemon", Code = 12 } ]; //Get the products from the both arrays //excluding duplicates. @@ -99,17 +99,17 @@ lemon 12 // // - Product[] products = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 }, - new Product { Name = "apple", Code = 9 }, - new Product { Name = "lemon", Code = 12 } }; + Product[] products = [ new() { Name = "apple", Code = 9 }, + new() { Name = "orange", Code = 4 }, + new() { Name = "apple", Code = 9 }, + new() { Name = "lemon", Code = 12 } ]; // Exclude duplicates. IEnumerable noduplicates = products.Distinct(new ProductComparer()); - foreach (var product in noduplicates) + foreach (Product product in noduplicates) Console.WriteLine(product.Name + " " + product.Code); /* @@ -121,17 +121,17 @@ lemon 12 // // - Product[] fruits = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 }, - new Product { Name = "lemon", Code = 12 } }; + Product[] fruits = [ new() { Name = "apple", Code = 9 }, + new() { Name = "orange", Code = 4 }, + new() { Name = "lemon", Code = 12 } ]; - Product apple = new Product { Name = "apple", Code = 9 }; - Product kiwi = new Product { Name = "kiwi", Code = 8 }; + Product apple = new() { Name = "apple", Code = 9 }; + Product kiwi = new() { Name = "kiwi", Code = 8 }; - ProductComparer prodc = new ProductComparer(); + ProductComparer prodc = new(); - bool hasApple = fruits.Contains(apple, prodc); - bool hasKiwi = fruits.Contains(kiwi, prodc); + var hasApple = fruits.Contains(apple, prodc); + var hasKiwi = fruits.Contains(kiwi, prodc); Console.WriteLine("Apple? " + hasApple); Console.WriteLine("Kiwi? " + hasKiwi); @@ -146,11 +146,11 @@ lemon 12 // // - Product[] fruits1 = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 }, - new Product { Name = "lemon", Code = 12 } }; + Product[] fruits1 = [ new() { Name = "apple", Code = 9 }, + new() { Name = "orange", Code = 4 }, + new() { Name = "lemon", Code = 12 } ]; - Product[] fruits2 = { new Product { Name = "apple", Code = 9 } }; + Product[] fruits2 = [new() { Name = "apple", Code = 9 }]; // Get all the elements from the first array // except for the elements from the second array. @@ -158,7 +158,7 @@ lemon 12 IEnumerable except = fruits1.Except(fruits2, new ProductComparer()); - foreach (var product in except) + foreach (Product product in except) Console.WriteLine(product.Name + " " + product.Code); /* @@ -172,13 +172,13 @@ lemon 12 // - Product[] storeA = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 } }; + Product[] storeA = [ new() { Name = "apple", Code = 9 }, + new() { Name = "orange", Code = 4 } ]; - Product[] storeB = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 } }; + Product[] storeB = [ new() { Name = "apple", Code = 9 }, + new() { Name = "orange", Code = 4 } ]; - bool equalAB = storeA.SequenceEqual(storeB, new ProductComparer()); + var equalAB = storeA.SequenceEqual(storeB, new ProductComparer()); Console.WriteLine("Equal? " + equalAB); diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs b/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs index 3ecc5c2cf63..53b46e24836 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs @@ -2,6 +2,8 @@ using System.Collections.Generic; using System.Linq; +namespace Comparers; + // public class MyProduct : IEquatable { @@ -11,10 +13,10 @@ public class MyProduct : IEquatable public bool Equals(MyProduct other) { //Check whether the compared object is null. - if (Object.ReferenceEquals(other, null)) return false; + if (other is null) return false; //Check whether the compared object references the same data. - if (Object.ReferenceEquals(this, other)) return true; + if (ReferenceEquals(this, other)) return true; //Check whether the products' properties are equal. return Code.Equals(other.Code) && Name.Equals(other.Name); @@ -25,20 +27,21 @@ public bool Equals(MyProduct other) public override int GetHashCode() { + //Get hash code for the Name field + var hashProductName = Name.GetHashCode(); - //Get hash code for the Name field if it is not null. - int hashProductName = Name == null ? 0 : Name.GetHashCode(); - - //Get hash code for the Code field. - int hashProductCode = Code.GetHashCode(); + //Get hash code for the Code field + var hashProductCode = Code.GetHashCode(); //Calculate the hash code for the product. return hashProductName ^ hashProductCode; } + + public override bool Equals(object obj) => Equals(obj as MyProduct); } // -class Program1 +static class Program1 { static void Main(string[] args) { @@ -46,11 +49,11 @@ static void Main(string[] args) // Some samples here need to use ProductA in conjunction with // ProductComparer, which implements IEqualityComparer (not IEquatable). // - ProductA[] store1 = { new ProductA { Name = "apple", Code = 9 }, - new ProductA { Name = "orange", Code = 4 } }; + ProductA[] store1 = [ new() { Name = "apple", Code = 9 }, + new() { Name = "orange", Code = 4 } ]; - ProductA[] store2 = { new ProductA { Name = "apple", Code = 9 }, - new ProductA { Name = "lemon", Code = 12 } }; + ProductA[] store2 = [ new() { Name = "apple", Code = 9 }, + new() { Name = "lemon", Code = 12 } ]; // // @@ -60,7 +63,7 @@ static void Main(string[] args) IEnumerable duplicates = store1.Intersect(store2); - foreach (var product in duplicates) + foreach (ProductA product in duplicates) Console.WriteLine(product.Name + " " + product.Code); /* @@ -76,7 +79,7 @@ apple 9 IEnumerable union = store1.Union(store2); - foreach (var product in union) + foreach (ProductA product in union) Console.WriteLine(product.Name + " " + product.Code); /* @@ -89,17 +92,17 @@ lemon 12 // // - MyProduct[] products = { new MyProduct { Name = "apple", Code = 9 }, - new MyProduct { Name = "orange", Code = 4 }, - new MyProduct { Name = "apple", Code = 9 }, - new MyProduct { Name = "lemon", Code = 12 } }; + MyProduct[] products = [ new() { Name = "apple", Code = 9 }, + new() { Name = "orange", Code = 4 }, + new() { Name = "apple", Code = 9 }, + new() { Name = "lemon", Code = 12 } ]; // Exclude duplicates. IEnumerable noduplicates = products.Distinct(); - foreach (var product in noduplicates) + foreach (MyProduct product in noduplicates) Console.WriteLine(product.Name + " " + product.Code); /* @@ -111,11 +114,11 @@ lemon 12 // // - ProductA[] fruits1 = { new ProductA { Name = "apple", Code = 9 }, - new ProductA { Name = "orange", Code = 4 }, - new ProductA { Name = "lemon", Code = 12 } }; + ProductA[] fruits1 = [ new() { Name = "apple", Code = 9 }, + new() { Name = "orange", Code = 4 }, + new() { Name = "lemon", Code = 12 } ]; - ProductA[] fruits2 = { new ProductA { Name = "apple", Code = 9 } }; + ProductA[] fruits2 = [new() { Name = "apple", Code = 9 }]; // Get all the elements from the first array // except for the elements from the second array. @@ -123,7 +126,7 @@ lemon 12 IEnumerable except = fruits1.Except(fruits2); - foreach (var product in except) + foreach (ProductA product in except) Console.WriteLine(product.Name + " " + product.Code); /* @@ -136,13 +139,13 @@ lemon 12 // - ProductA[] storeA = { new ProductA { Name = "apple", Code = 9 }, - new ProductA { Name = "orange", Code = 4 } }; + ProductA[] storeA = [ new() { Name = "apple", Code = 9 }, + new() { Name = "orange", Code = 4 } ]; - ProductA[] storeB = { new ProductA { Name = "apple", Code = 9 }, - new ProductA { Name = "orange", Code = 4 } }; + ProductA[] storeB = [ new() { Name = "apple", Code = 9 }, + new() { Name = "orange", Code = 4 } ]; - bool equalAB = storeA.SequenceEqual(storeB); + var equalAB = storeA.SequenceEqual(storeB); Console.WriteLine("Equal? " + equalAB); @@ -166,7 +169,7 @@ public bool Equals(ProductA other) if (other is null) return false; - return this.Name == other.Name && this.Code == other.Code; + return Name == other.Name && Code == other.Code; } public override bool Equals(object obj) => Equals(obj as ProductA); diff --git a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj new file mode 100644 index 00000000000..0eddc23065a --- /dev/null +++ b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj @@ -0,0 +1,15 @@ + + + + Library + net8.0 + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + \ No newline at end of file diff --git a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/Project.csproj b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/Project.csproj deleted file mode 100644 index c02dc5044e7..00000000000 --- a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/Project.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Library - net6.0 - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/igrouping.cs b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/igrouping.cs index 955d07ed9bc..ec51757f6ae 100644 --- a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/igrouping.cs +++ b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/igrouping.cs @@ -8,19 +8,17 @@ namespace SequenceExamples { static class IGrouping { - static void Main(string[] args) - { + static void Main() => //Console.WriteLine("\n"); //GroupKey(); EnumerateGroup(); - } private static void EnumerateGroup() { // // Get an IGrouping object. IGrouping group = - typeof(String).GetMembers(). + typeof(string).GetMembers(). GroupBy(member => member.MemberType). First(); @@ -59,7 +57,7 @@ private static void GroupKey() // // Get a sequence of IGrouping objects. IEnumerable> memberQuery = - typeof(String).GetMembers(). + typeof(string).GetMembers(). GroupBy(member => member.MemberType); // Output the key of each IGrouping object and the count of values. @@ -78,7 +76,7 @@ private static void GroupKey() private static void Test() { IOrderedEnumerable> memberQuery = - typeof(String).GetMembers(). + typeof(string).GetMembers(). GroupBy(member => member.MemberType). OrderBy(group => group.Count()); diff --git a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs index 7c89e4efe09..38cc3039746 100644 --- a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs +++ b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs @@ -7,10 +7,7 @@ namespace SequenceExamples { static class ILookup { - static void Main(string[] args) - { - ILookupExample(); - } + static void Main() => ILookupExample(); // class Package @@ -23,11 +20,12 @@ class Package public static void ILookupExample() { // Create a list of Packages to put into an ILookup data structure. - List packages = new List { new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L }, + List packages = + [ new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L }, new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L }, new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L }, new Package { Company = "Contoso Pharmaceuticals", Weight = 9.3, TrackingNumber = 670053128L }, - new Package { Company = "Wide World Importers", Weight = 33.8, TrackingNumber = 4665518773L } }; + new Package { Company = "Wide World Importers", Weight = 33.8, TrackingNumber = 4665518773L } ]; // Create a Lookup to organize the packages. Use the first character of Company as the key value. // Select Company appended to TrackingNumber for each element value in the ILookup object. @@ -37,7 +35,7 @@ public static void ILookupExample() ); // Iterate through each value in the ILookup and output the contents. - foreach (var packageGroup in packageLookup) + foreach (IGrouping packageGroup in packageLookup) { // Print the key value. Console.WriteLine(packageGroup.Key); diff --git a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj new file mode 100644 index 00000000000..0eddc23065a --- /dev/null +++ b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj @@ -0,0 +1,15 @@ + + + + Library + net8.0 + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + \ No newline at end of file diff --git a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/Project.csproj b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/Project.csproj deleted file mode 100644 index c02dc5044e7..00000000000 --- a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/Project.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Library - net6.0 - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.cs b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.cs index 404ecfd30fb..d0b45b843ac 100644 --- a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.cs +++ b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.cs @@ -7,21 +7,19 @@ namespace IOrderedSequence { static class IOrderedSequence { - static void Main(string[] args) - { - Example2(); - } + static void Main() => Example2(); static void Example1() { // // Create an array of strings to sort. - string[] fruits = { "apricot", "orange", "banana", "mango", "apple", "grape", "strawberry" }; + string[] fruits = ["apricot", "orange", "banana", "mango", "apple", "grape", "strawberry"]; // Sort the strings first by their length and then alphabetically // by passing the identity selector function. IOrderedEnumerable sortedFruits1 = - fruits.OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit); + fruits.OrderBy(fruit => fruit.Length) + .ThenBy(fruit => fruit); // Output the resulting sequence of strings. foreach (string fruit in sortedFruits1) @@ -46,7 +44,7 @@ static void Example2() { // // Create an array of strings to sort. - string[] fruits = { "apricot", "orange", "banana", "mango", "apple", "grape", "strawberry" }; + string[] fruits = ["apricot", "orange", "banana", "mango", "apple", "grape", "strawberry"]; // First sort the strings by their length. IOrderedEnumerable sortedFruits2 = fruits.OrderBy(fruit => fruit.Length); diff --git a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj new file mode 100644 index 00000000000..0eddc23065a --- /dev/null +++ b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj @@ -0,0 +1,15 @@ + + + + Library + net8.0 + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + \ No newline at end of file diff --git a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/Project.csproj b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/Project.csproj deleted file mode 100644 index c02dc5044e7..00000000000 --- a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/Project.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Library - net6.0 - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/Linq - Copy.txt b/snippets/csharp/System.Linq/Linq - Copy.txt new file mode 100644 index 00000000000..c6de5d07ea9 --- /dev/null +++ b/snippets/csharp/System.Linq/Linq - Copy.txt @@ -0,0 +1,61 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.11.35017.193 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AggregateTSource", "Queryable\AggregateTSource\AggregateTSource.csproj", "{DF972B67-A03E-4335-9C77-55B23CB2A61B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Comparers", "Enumerable\Comparers\Comparers.csproj", "{33FFC016-737E-458A-B934-51906302BD24}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Enumerable", "Enumerable\AggregateTSource\Enumerable.csproj", "{1FB32EED-539F-405D-A7E0-CB8886178B13}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IGrouping", "IGroupingTKey,TElement\Overview\IGrouping.csproj", "{272B9F43-D02D-4D44-BF4F-80118560CA4D}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ILookup", "ILookupTKey,TElement\Overview\ILookup.csproj", "{EFF5E75B-DC97-4973-9AA0-D17A7246D727}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IOrderedEnumerable", "IOrderedEnumerableTElement\Overview\IOrderedEnumerable.csproj", "{A0D8E2EB-8EBA-46F1-AC80-5D4F54F2B344}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{0AADD544-5364-466F-B46A-E3D0B8A25A0E}" + ProjectSection(SolutionItems) = preProject + ..\..\..\..\..\temp\.editorconfig = ..\..\..\..\..\temp\.editorconfig + ..\..\..\..\..\temp\.editorconfigMINE = ..\..\..\..\..\temp\.editorconfigMINE + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DF972B67-A03E-4335-9C77-55B23CB2A61B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DF972B67-A03E-4335-9C77-55B23CB2A61B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DF972B67-A03E-4335-9C77-55B23CB2A61B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DF972B67-A03E-4335-9C77-55B23CB2A61B}.Release|Any CPU.Build.0 = Release|Any CPU + {33FFC016-737E-458A-B934-51906302BD24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {33FFC016-737E-458A-B934-51906302BD24}.Debug|Any CPU.Build.0 = Debug|Any CPU + {33FFC016-737E-458A-B934-51906302BD24}.Release|Any CPU.ActiveCfg = Release|Any CPU + {33FFC016-737E-458A-B934-51906302BD24}.Release|Any CPU.Build.0 = Release|Any CPU + {1FB32EED-539F-405D-A7E0-CB8886178B13}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1FB32EED-539F-405D-A7E0-CB8886178B13}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1FB32EED-539F-405D-A7E0-CB8886178B13}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1FB32EED-539F-405D-A7E0-CB8886178B13}.Release|Any CPU.Build.0 = Release|Any CPU + {272B9F43-D02D-4D44-BF4F-80118560CA4D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {272B9F43-D02D-4D44-BF4F-80118560CA4D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {272B9F43-D02D-4D44-BF4F-80118560CA4D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {272B9F43-D02D-4D44-BF4F-80118560CA4D}.Release|Any CPU.Build.0 = Release|Any CPU + {EFF5E75B-DC97-4973-9AA0-D17A7246D727}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EFF5E75B-DC97-4973-9AA0-D17A7246D727}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EFF5E75B-DC97-4973-9AA0-D17A7246D727}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EFF5E75B-DC97-4973-9AA0-D17A7246D727}.Release|Any CPU.Build.0 = Release|Any CPU + {A0D8E2EB-8EBA-46F1-AC80-5D4F54F2B344}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A0D8E2EB-8EBA-46F1-AC80-5D4F54F2B344}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A0D8E2EB-8EBA-46F1-AC80-5D4F54F2B344}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A0D8E2EB-8EBA-46F1-AC80-5D4F54F2B344}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {1C179DD0-BF65-4A4C-89EF-7EAAE0A18CEE} + EndGlobalSection +EndGlobal diff --git a/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Project.csproj b/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Project.csproj deleted file mode 100644 index c02dc5044e7..00000000000 --- a/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Project.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Library - net6.0 - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj b/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj new file mode 100644 index 00000000000..48a0fef22a0 --- /dev/null +++ b/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj @@ -0,0 +1,15 @@ + + + + Library + net8.0 + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/Project.csproj b/snippets/csharp/System.Linq/Queryable/AggregateTSource/Project.csproj deleted file mode 100644 index c02dc5044e7..00000000000 --- a/snippets/csharp/System.Linq/Queryable/AggregateTSource/Project.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Library - net6.0 - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs b/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs index 9cdf0985ad1..d23b3866a81 100644 --- a/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs +++ b/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs @@ -4,10 +4,10 @@ namespace QueryableExamples { - public class Program + static class Program { // This part is just for testing the examples - static void Main(string[] args) + static void Main() { All.AllEx1(); All2.AllEx2(); @@ -17,7 +17,7 @@ static void Main(string[] args) static void AggregateEx1() { // - string sentence = "the quick brown fox jumps over the lazy dog"; + const string sentence = "the quick brown fox jumps over the lazy dog"; // Split the string into individual words. string[] words = sentence.Split(' '); @@ -40,7 +40,7 @@ static void AggregateEx1() static void AggregateEx2() { // - int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 }; + int[] ints = [4, 8, 8, 3, 9, 0, 7, 8, 2]; // Count the even numbers in the array, using a seed value of 0. int numEven = @@ -60,16 +60,16 @@ static void AggregateEx2() static void AggregateEx3() { // - string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" }; + string[] fruits = ["apple", "mango", "orange", "passionfruit", "grape"]; // Determine whether any string in the array is longer than "banana". string longestName = - fruits.AsQueryable().Aggregate( - "banana", - (longest, next) => next.Length > longest.Length ? next : longest, - // Return the final result as an uppercase string. - fruit => fruit.ToUpper() - ); + fruits.AsQueryable() + .Aggregate( + "banana", + (longest, next) => next.Length > longest.Length ? next : longest, + // Return the final result as an uppercase string. + fruit => fruit.ToUpper()); Console.WriteLine( "The fruit with the longest name is {0}.", @@ -96,13 +96,13 @@ class Pet public static void AllEx1() { // Create an array of Pets. - Pet[] pets = { new Pet { Name="Barley", Age=10 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=6 } }; + Pet[] pets = [ new() { Name="Barley", Age=10 }, + new() { Name="Boots", Age=4 }, + new() { Name="Whiskers", Age=6 } ]; // Determine whether all pet names in the array start with 'B'. bool allStartWithB = - pets.AsQueryable().All(pet => pet.Name.StartsWith("B")); + pets.AsQueryable().All(pet => pet.Name.StartsWith('B')); Console.WriteLine( "{0} pet names start with 'B'.", @@ -132,19 +132,19 @@ class Person public static void AllEx2() { - List people = new List - { new Person { LastName = "Haas", - Pets = new Pet[] { new Pet { Name="Barley", Age=10 }, - new Pet { Name="Boots", Age=14 }, - new Pet { Name="Whiskers", Age=6 }}}, + List people = + [ new Person { LastName = "Haas", + Pets = [ new() { Name="Barley", Age=10 }, + new() { Name="Boots", Age=14 }, + new() { Name="Whiskers", Age=6 }]}, new Person { LastName = "Fakhouri", - Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}}, + Pets = [new() { Name = "Snowball", Age = 1}]}, new Person { LastName = "Antebi", - Pets = new Pet[] { new Pet { Name = "Belle", Age = 8} }}, + Pets = [new() { Name = "Belle", Age = 8}]}, new Person { LastName = "Philips", - Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2}, - new Pet { Name = "Rover", Age = 13}} } - }; + Pets = [ new() { Name = "Sweetie", Age = 2}, + new() { Name = "Rover", Age = 13}] } + ]; // Determine which people have pets that are all older than 5. IEnumerable names = from person in people @@ -165,12 +165,12 @@ where person.Pets.AsQueryable().All(pet => pet.Age > 5) #endregion #region Any - class Any1 + static class Any1 { public static void AnyEx1() { // - List numbers = new List { 1, 2 }; + List numbers = [1, 2]; // Determine if the list contains any elements. bool hasElements = numbers.AsQueryable().Any(); @@ -199,19 +199,19 @@ class Person public static void AnyEx2() { - List people = new List - { new Person { LastName = "Haas", - Pets = new Pet[] { new Pet { Name="Barley", Age=10 }, - new Pet { Name="Boots", Age=14 }, - new Pet { Name="Whiskers", Age=6 }}}, + List people = + [ new Person { LastName = "Haas", + Pets = [ new() { Name="Barley", Age=10 }, + new() { Name="Boots", Age=14 }, + new() { Name="Whiskers", Age=6 }]}, new Person { LastName = "Fakhouri", - Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}}, + Pets = [new() { Name = "Snowball", Age = 1}]}, new Person { LastName = "Antebi", - Pets = new Pet[] { }}, + Pets = []}, new Person { LastName = "Philips", - Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2}, - new Pet { Name = "Rover", Age = 13}} } - }; + Pets = [ new() { Name = "Sweetie", Age = 2}, + new() { Name = "Rover", Age = 13}] } + ]; // Determine which people have a non-empty Pet array. IEnumerable names = from person in people @@ -245,13 +245,13 @@ public static void AnyEx3() { // Create an array of Pet objects. Pet[] pets = - { new Pet { Name="Barley", Age=8, Vaccinated=true }, - new Pet { Name="Boots", Age=4, Vaccinated=false }, - new Pet { Name="Whiskers", Age=1, Vaccinated=false } }; + [ new() { Name="Barley", Age=8, Vaccinated=true }, + new() { Name="Boots", Age=4, Vaccinated=false }, + new() { Name="Whiskers", Age=1, Vaccinated=false } ]; // Determine whether any pets over age 1 are also unvaccinated. bool unvaccinated = - pets.AsQueryable().Any(p => p.Age > 1 && p.Vaccinated == false); + pets.AsQueryable().Any(p => p.Age > 1 && !p.Vaccinated); Console.WriteLine( "There {0} unvaccinated animals over age one.", @@ -270,7 +270,7 @@ public static void AnyEx3() static void AsQueryableEx1() { // - List grades = new List { 78, 92, 100, 37, 81 }; + List grades = [78, 92, 100, 37, 81]; // Convert the List to an IQueryable. IQueryable iqueryable = grades.AsQueryable(); @@ -299,7 +299,7 @@ static void AsQueryableEx1() static void AverageEx1() { // - List grades = new List { 78, 92, 100, 37, 81 }; + List grades = [78, 92, 100, 37, 81]; double average = grades.AsQueryable().Average(); @@ -315,7 +315,7 @@ static void AverageEx1() static void AverageEx2() { // - long?[] longs = { null, 10007L, 37L, 399846234235L }; + long?[] longs = [null, 10007L, 37L, 399846234235L]; double? average = longs.AsQueryable().Average(); @@ -331,7 +331,7 @@ static void AverageEx2() static void AverageEx3() { // - string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; + string[] fruits = ["apple", "banana", "mango", "orange", "passionfruit", "grape"]; // Determine the average string length in the array. double average = fruits.AsQueryable().Average(s => s.Length); @@ -351,7 +351,7 @@ static void AverageEx3() static void CastEx1() { // Get a list of the methods available on the String type. - List methods = typeof(String).GetMethods().ToList(); + List methods = [.. typeof(string).GetMethods()]; // Cast each MethodInfo object to a MemberInfo object. // Then select the names of those methods whose names @@ -388,7 +388,7 @@ static void CastEx2() // Create a list of objects. List words = - new List { "green", "blue", "violet" }; + ["green", "blue", "violet"]; // Cast the objects in the list to type 'string' // and project the first letter of each string. @@ -424,18 +424,18 @@ class Pet // This method creates and returns an array of Pet objects. static Pet[] GetCats() { - Pet[] cats = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] cats = [ new() { Name="Barley", Age=8 }, + new() { Name="Boots", Age=4 }, + new() { Name="Whiskers", Age=1 } ]; return cats; } // This method creates and returns an array of Pet objects. static Pet[] GetDogs() { - Pet[] dogs = { new Pet { Name="Bounder", Age=3 }, - new Pet { Name="Snoopy", Age=14 }, - new Pet { Name="Fido", Age=9 } }; + Pet[] dogs = [ new() { Name="Bounder", Age=3 }, + new() { Name="Snoopy", Age=14 }, + new() { Name="Fido", Age=9 } ]; return dogs; } @@ -475,7 +475,8 @@ public static void ConcatEx2() // Concatenate a collection of cat names to a // collection of dog names by using SelectMany(). IEnumerable query = - new[] { cats.Select(cat => cat.Name), dogs.Select(dog => dog.Name) } + new[] { cats.Select(cat => cat.Name), + dogs.Select(dog => dog.Name) } .AsQueryable().SelectMany(name => name); foreach (string name in query) @@ -499,11 +500,11 @@ public static void ConcatEx2() static void ContainsEx1() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; // The string to search for in the array. - string mango = "mango"; + const string mango = "mango"; bool hasMango = fruits.AsQueryable().Contains(mango); @@ -524,8 +525,8 @@ static void ContainsEx1() static void CountEx1() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; int numberOfFruits = fruits.AsQueryable().Count(); @@ -552,13 +553,13 @@ class Pet public static void CountEx2() { // Create an array of Pet objects. - Pet[] pets = { new Pet { Name="Barley", Vaccinated=true }, - new Pet { Name="Boots", Vaccinated=false }, - new Pet { Name="Whiskers", Vaccinated=false } }; + Pet[] pets = [ new() { Name="Barley", Vaccinated=true }, + new() { Name="Boots", Vaccinated=false }, + new() { Name="Whiskers", Vaccinated=false } ]; // Count the number of unvaccinated pets in the array. int numberUnvaccinated = - pets.AsQueryable().Count(p => p.Vaccinated == false); + pets.AsQueryable().Count(p => !p.Vaccinated); Console.WriteLine( "There are {0} unvaccinated animals.", @@ -587,18 +588,17 @@ public static void DefaultIfEmptyEx1() { // Create a list of Pet objects. List pets = - new List{ new Pet { Name="Barley", Age=8 }, + [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + new Pet { Name="Whiskers", Age=1 } ]; // Call DefaultIfEmtpy() on the collection that Select() // returns, so that if the initial list is empty, there // will always be at least one item in the returned array. string[] names = - pets.AsQueryable() + [.. pets.AsQueryable() .Select(pet => pet.Name) - .DefaultIfEmpty() - .ToArray(); + .DefaultIfEmpty()]; string first = names[0]; Console.WriteLine(first); @@ -616,30 +616,28 @@ public static void DefaultIfEmptyEx1a() // // Create a list of Pet objects. List pets = - new List{ new Pet { Name="Barley", Age=8 }, + [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + new Pet { Name="Whiskers", Age=1 } ]; // This query selects only those pets that are 10 or older. // In case there are no pets that meet that criteria, call // DefaultIfEmpty(). This code passes an (optional) default // value to DefaultIfEmpty(). string[] oldPets = - pets.AsQueryable() + [.. pets.AsQueryable() .Where(pet => pet.Age >= 10) .Select(pet => pet.Name) - .DefaultIfEmpty("[EMPTY]") - .ToArray(); + .DefaultIfEmpty("[EMPTY]")]; Console.WriteLine("First query: " + oldPets[0]); // This query selects only those pets that are 10 or older. // This code does not call DefaultIfEmpty(). string[] oldPets2 = - pets.AsQueryable() + [.. pets.AsQueryable() .Where(pet => pet.Age >= 10) - .Select(pet => pet.Name) - .ToArray(); + .Select(pet => pet.Name)]; // There may be no elements in the array, so directly // accessing element 0 may throw an exception. @@ -668,7 +666,7 @@ public static void DefaultIfEmptyEx1a() static void DistinctEx1() { // - List ages = new List { 21, 46, 46, 55, 17, 21, 55, 55 }; + List ages = [21, 46, 46, 55, 17, 21, 55, 55]; IEnumerable distinctAges = ages.AsQueryable().Distinct(); @@ -695,11 +693,11 @@ static void DistinctEx1() static void ElementAtEx1() { // - string[] names = { "Hartono, Tommy", "Adams, Terry", + string[] names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; + "Hedlund, Magnus", "Ito, Shu" ]; - Random random = new Random(DateTime.Now.Millisecond); + Random random = new(DateTime.Now.Millisecond); string name = names.AsQueryable().ElementAt(random.Next(0, names.Length)); @@ -721,18 +719,18 @@ Yours may be different due to the use of Random. static void ElementAtOrDefaultEx1() { // - string[] names = { "Hartono, Tommy", "Adams, Terry", + string[] names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; + "Hedlund, Magnus", "Ito, Shu" ]; - int index = 20; + const int index = 20; string name = names.AsQueryable().ElementAtOrDefault(index); Console.WriteLine( "The name chosen at index {0} is '{1}'.", index, - String.IsNullOrEmpty(name) ? "[NONE AT THIS INDEX]" : name); + string.IsNullOrEmpty(name) ? "[NONE AT THIS INDEX]" : name); /* This code produces the following output: @@ -748,8 +746,8 @@ The name chosen at index 20 is '[NONE AT THIS INDEX]'. static void ExceptEx1() { // - double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 }; - double[] numbers2 = { 2.2 }; + double[] numbers1 = [2.0, 2.1, 2.2, 2.3, 2.4, 2.5]; + double[] numbers2 = [2.2]; // Get the numbers from the first array that // are NOT in the second array. @@ -777,8 +775,8 @@ static void ExceptEx1() static void FirstEx1() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 435, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 435, 67, 12, 19 ]; int first = numbers.AsQueryable().First(); @@ -796,8 +794,8 @@ static void FirstEx1() static void FirstEx2() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 435, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 435, 67, 12, 19 ]; // Get the first number in the array that is greater than 80. int first = numbers.AsQueryable().First(number => number > 80); @@ -819,7 +817,7 @@ static void FirstOrDefaultEx1() { // // Create an empty array. - int[] numbers = { }; + int[] numbers = []; // Get the first item in the array, or else the // default value for type int (0). int first = numbers.AsQueryable().FirstOrDefault(); @@ -838,9 +836,9 @@ static void FirstOrDefaultEx1() static void FirstOrDefaultEx2() { // - string[] names = { "Hartono, Tommy", "Adams, Terry", + string[] names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; + "Hedlund, Magnus", "Ito, Shu" ]; // Get the first string in the array that is longer // than 20 characters, or the default value for type @@ -873,7 +871,7 @@ There is NOT a name that is longer than 30 characters. static void FirstOrDefaultEx3() { // - List months = new List { }; + List months = []; // Setting the default value to 1 after the query. int firstMonth1 = months.AsQueryable().FirstOrDefault(); @@ -912,17 +910,18 @@ public static void GroupByEx1() { // Create a list of Pet objects. List pets = - new List{ new Pet { Name="Barley", Age=8 }, + [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 }, - new Pet { Name="Daisy", Age=4 } }; + new Pet { Name="Daisy", Age=4 } ]; // Group the pets using Pet.Age as the key. // Use Pet.Name as the value for each entry. - var query = pets.AsQueryable().GroupBy(pet => pet.Age); + IQueryable> query = pets.AsQueryable() + .GroupBy(pet => pet.Age); // Iterate over each IGrouping in the collection. - foreach (var ageGroup in query) + foreach (IGrouping ageGroup in query) { Console.WriteLine("Age group: {0} Number of pets: {1}", ageGroup.Key, ageGroup.Count()); } @@ -953,10 +952,10 @@ public static void GroupByEx2() { // Create a list of Pet objects. List pets = - new List{ new Pet { Name="Barley", Age=8 }, + [ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 }, - new Pet { Name="Daisy", Age=4 } }; + new Pet { Name="Daisy", Age=4 } ]; // Group the pets using Pet.Age as the key. // Use Pet.Name as the value for each entry. @@ -1004,10 +1003,10 @@ public static void GroupByEx3() { // Create a list of pets. List petsList = - new List{ new Pet { Name="Barley", Age=8.3 }, + [ new Pet { Name="Barley", Age=8.3 }, new Pet { Name="Boots", Age=4.9 }, new Pet { Name="Whiskers", Age=1.5 }, - new Pet { Name="Daisy", Age=4.3 } }; + new Pet { Name="Daisy", Age=4.3 } ]; // Group Pet objects by the Math.Floor of their age. // Then project an anonymous type from each group @@ -1067,10 +1066,10 @@ public static void GroupByEx4() { // Create a list of pets. List petsList = - new List{ new Pet { Name="Barley", Age=8.3 }, + [ new Pet { Name="Barley", Age=8.3 }, new Pet { Name="Boots", Age=4.9 }, new Pet { Name="Whiskers", Age=1.5 }, - new Pet { Name="Daisy", Age=4.3 } }; + new Pet { Name="Daisy", Age=4.3 } ]; // Group Pet.Age values by the Math.Floor of the age. // Then project an anonymous type from each group @@ -1135,17 +1134,17 @@ class Pet public static void GroupJoinEx1() { - Person magnus = new Person { Name = "Hedlund, Magnus" }; - Person terry = new Person { Name = "Adams, Terry" }; - Person charlotte = new Person { Name = "Weiss, Charlotte" }; + Person magnus = new() { Name = "Hedlund, Magnus" }; + Person terry = new() { Name = "Adams, Terry" }; + Person charlotte = new() { Name = "Weiss, Charlotte" }; - Pet barley = new Pet { Name = "Barley", Owner = terry }; - Pet boots = new Pet { Name = "Boots", Owner = terry }; - Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; + Pet barley = new() { Name = "Barley", Owner = terry }; + Pet boots = new() { Name = "Boots", Owner = terry }; + Pet whiskers = new() { Name = "Whiskers", Owner = charlotte }; + Pet daisy = new() { Name = "Daisy", Owner = magnus }; - List people = new List { magnus, terry, charlotte }; - List pets = new List { barley, boots, whiskers, daisy }; + List people = [magnus, terry, charlotte]; + List pets = [barley, boots, whiskers, daisy]; // Create a list where each element is an anonymous // type that contains a person's name and a collection @@ -1191,8 +1190,8 @@ public static void GroupJoinEx1() static void IntersectEx1() { // - int[] id1 = { 44, 26, 92, 30, 71, 38 }; - int[] id2 = { 39, 59, 83, 47, 26, 4, 30 }; + int[] id1 = [44, 26, 92, 30, 71, 38]; + int[] id2 = [39, 59, 83, 47, 26, 4, 30]; // Get the numbers that occur in both arrays (id1 and id2). IEnumerable both = id1.AsQueryable().Intersect(id2); @@ -1228,17 +1227,17 @@ class Pet public static void JoinEx1() { - Person magnus = new Person { Name = "Hedlund, Magnus" }; - Person terry = new Person { Name = "Adams, Terry" }; - Person charlotte = new Person { Name = "Weiss, Charlotte" }; + Person magnus = new() { Name = "Hedlund, Magnus" }; + Person terry = new() { Name = "Adams, Terry" }; + Person charlotte = new() { Name = "Weiss, Charlotte" }; - Pet barley = new Pet { Name = "Barley", Owner = terry }; - Pet boots = new Pet { Name = "Boots", Owner = terry }; - Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; + Pet barley = new() { Name = "Barley", Owner = terry }; + Pet boots = new() { Name = "Boots", Owner = terry }; + Pet whiskers = new() { Name = "Whiskers", Owner = charlotte }; + Pet daisy = new() { Name = "Daisy", Owner = magnus }; - List people = new List { magnus, terry, charlotte }; - List pets = new List { barley, boots, whiskers, daisy }; + List people = [magnus, terry, charlotte]; + List pets = [barley, boots, whiskers, daisy]; // Join the list of Person objects and the list of Pet objects // to create a list of person-pet pairs where each element is @@ -1276,8 +1275,8 @@ public static void JoinEx1() static void LastEx1() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 67, 12, 19 ]; int last = numbers.AsQueryable().Last(); @@ -1295,8 +1294,8 @@ static void LastEx1() static void LastEx2() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 67, 12, 19 ]; // Get the last number in the array that is greater than 80. int last = numbers.AsQueryable().Last(num => num > 80); @@ -1318,14 +1317,14 @@ static void LastOrDefaultEx1() { // // Create an empty array. - string[] fruits = { }; + string[] fruits = []; // Get the last item in the array, or else the default // value for type string (null). string last = fruits.AsQueryable().LastOrDefault(); Console.WriteLine( - String.IsNullOrEmpty(last) ? "[STRING IS NULL OR EMPTY]" : last); + string.IsNullOrEmpty(last) ? "[STRING IS NULL OR EMPTY]" : last); /* This code produces the following output: @@ -1339,19 +1338,21 @@ [STRING IS NULL OR EMPTY] static void LastOrDefaultEx2() { // - double[] numbers = { 49.6, 52.3, 51.0, 49.4, 50.2, 48.3 }; + double[] numbers = [49.6, 52.3, 51.0, 49.4, 50.2, 48.3]; // Get the last number in the array that rounds to 50.0, // or else the default value for type double (0.0). double last50 = - numbers.AsQueryable().LastOrDefault(n => Math.Round(n) == 50.0); + numbers.AsQueryable() + .LastOrDefault(n => Math.Round(n) == 50.0); Console.WriteLine("The last number that rounds to 50 is {0}.", last50); // Get the last number in the array that rounds to 40.0, // or else the default value for type double (0.0). double last40 = - numbers.AsQueryable().LastOrDefault(n => Math.Round(n) == 40.0); + numbers.AsQueryable() + .LastOrDefault(n => Math.Round(n) == 40.0); Console.WriteLine( "The last number that rounds to 40 is {0}.", @@ -1370,7 +1371,7 @@ The last number that rounds to 40 is [DOES NOT EXIST]. static void LastOrDefaultEx3() { // - List daysOfMonth = new List { }; + List daysOfMonth = []; // Setting the default value to 1 after the query. int lastDay1 = daysOfMonth.AsQueryable().LastOrDefault(); @@ -1398,8 +1399,8 @@ The value of the lastDay2 variable is 1 public static void LongCountEx1() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; long count = fruits.AsQueryable().LongCount(); @@ -1425,14 +1426,15 @@ class Pet public static void LongCountEx2() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ new() { Name="Barley", Age=8 }, + new() { Name="Boots", Age=4 }, + new() { Name="Whiskers", Age=1 } ]; const int Age = 3; // Count the number of Pet objects where Pet.Age is greater than 3. - long count = pets.AsQueryable().LongCount(pet => pet.Age > Age); + long count = pets.AsQueryable() + .LongCount(pet => pet.Age > Age); Console.WriteLine("There are {0} animals over age {1}.", count, Age); } @@ -1451,7 +1453,7 @@ There are 2 animals over age 3. static void MaxEx1() { // - List longs = new List { 4294967296L, 466855135L, 81125L }; + List longs = [4294967296L, 466855135L, 81125L]; long max = longs.AsQueryable().Max(); @@ -1477,9 +1479,9 @@ class Pet public static void MaxEx2() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ new() { Name="Barley", Age=8 }, + new() { Name="Boots", Age=4 }, + new() { Name="Whiskers", Age=1 } ]; // Add Pet.Age to the length of Pet.Name // to determine the "maximum" Pet object in the array. @@ -1506,7 +1508,7 @@ The maximum pet age plus name length is 14. static void MinEx1() { // - double[] doubles = { 1.5E+104, 9E+103, -2E+103 }; + double[] doubles = [1.5E+104, 9E+103, -2E+103]; double min = doubles.AsQueryable().Min(); @@ -1532,9 +1534,9 @@ class Pet public static void MinEx2() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ new() { Name="Barley", Age=8 }, + new() { Name="Boots", Age=4 }, + new() { Name="Whiskers", Age=1 } ]; // Get the Pet object that has the smallest Age value. int min = pets.AsQueryable().Min(pet => pet.Age); @@ -1557,7 +1559,7 @@ static void OfTypeEx1() { // // Create a list of MemberInfo objects. - List members = typeof(String).GetMembers().ToList(); + List members = [.. typeof(string).GetMembers()]; // Return only those items that can be cast to type PropertyInfo. IQueryable propertiesOnly = @@ -1591,9 +1593,9 @@ class Pet public static void OrderByEx1() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ new() { Name="Barley", Age=8 }, + new() { Name="Boots", Age=4 }, + new() { Name="Whiskers", Age=1 } ]; // Sort the Pet objects in the array by Pet.Age. IEnumerable query = @@ -1659,7 +1661,7 @@ public int Compare(decimal d1, decimal d2) } if (fractional1 == fractional2) - return Decimal.Compare(d1, d2); + return decimal.Compare(d1, d2); else if (fractional1 > fractional2) return 1; else @@ -1670,7 +1672,7 @@ public int Compare(decimal d1, decimal d2) public static void OrderByDescendingEx1() { List decimals = - new List { 6.2m, 8.3m, 0.5m, 1.3m, 6.3m, 9.7m }; + [6.2m, 8.3m, 0.5m, 1.3m, 6.3m, 9.7m]; // Sort the decimal values in descending order // by using a custom comparer. @@ -1701,7 +1703,7 @@ public static void OrderByDescendingEx1() static void ReverseEx1() { // - char[] apple = { 'a', 'p', 'p', 'l', 'e' }; + char[] apple = ['a', 'p', 'p', 'l', 'e']; // Reverse the order of the characters in the collection. IQueryable reversed = apple.AsQueryable().Reverse(); @@ -1725,7 +1727,7 @@ static void SelectEx1() { // List range = - new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Project the square of each int value. IEnumerable squares = @@ -1755,8 +1757,8 @@ static void SelectEx1() static void SelectEx2() { // - string[] fruits = { "apple", "banana", "mango", "orange", - "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", "orange", + "passionfruit", "grape" ]; // Project an anonymous type that contains the // index of the string in the source array, and @@ -1792,22 +1794,23 @@ static class SelectMany1 class PetOwner { public string Name { get; set; } - public List Pets { get; set; } + public List Pets { get; set; } } public static void SelectManyEx1() { PetOwner[] petOwners = - { new PetOwner { Name="Higa, Sidney", - Pets = new List{ "Scruffy", "Sam" } }, - new PetOwner { Name="Ashkenazi, Ronen", - Pets = new List{ "Walker", "Sugar" } }, - new PetOwner { Name="Price, Vernette", - Pets = new List{ "Scratches", "Diesel" } } }; + [ new() { Name="Higa, Sidney", + Pets = ["Scruffy", "Sam"] }, + new() { Name="Ashkenazi, Ronen", + Pets = ["Walker", "Sugar"] }, + new() { Name="Price, Vernette", + Pets = ["Scratches", "Diesel"] } ]; // Query using SelectMany(). IEnumerable query1 = - petOwners.AsQueryable().SelectMany(petOwner => petOwner.Pets); + petOwners.AsQueryable() + .SelectMany(petOwner => petOwner.Pets); Console.WriteLine("Using SelectMany():"); @@ -1817,14 +1820,15 @@ public static void SelectManyEx1() Console.WriteLine(pet); // This code shows how to use Select() instead of SelectMany(). - IEnumerable> query2 = - petOwners.AsQueryable().Select(petOwner => petOwner.Pets); + IEnumerable> query2 = + petOwners.AsQueryable() + .Select(petOwner => petOwner.Pets); Console.WriteLine("\nUsing Select():"); // Notice that two foreach loops are required to iterate through // the results because the query returns a collection of arrays. - foreach (List petList in query2) + foreach (List petList in query2) { foreach (string pet in petList) { @@ -1871,14 +1875,14 @@ class PetOwner public static void SelectManyEx2() { PetOwner[] petOwners = - { new PetOwner { Name="Higa, Sidney", - Pets = new List{ "Scruffy", "Sam" } }, - new PetOwner { Name="Ashkenazi, Ronen", - Pets = new List{ "Walker", "Sugar" } }, - new PetOwner { Name="Price, Vernette", - Pets = new List{ "Scratches", "Diesel" } }, - new PetOwner { Name="Hines, Patrick", - Pets = new List{ "Dusty" } } }; + [ new() { Name="Higa, Sidney", + Pets = ["Scruffy", "Sam"] }, + new() { Name="Ashkenazi, Ronen", + Pets = ["Walker", "Sugar"] }, + new() { Name="Price, Vernette", + Pets = ["Scratches", "Diesel"] }, + new() { Name="Hines, Patrick", + Pets = ["Dusty"] } ]; // For each PetOwner element in the source array, // project a sequence of strings where each string @@ -1925,22 +1929,22 @@ class Pet public static void SelectManyEx3() { PetOwner[] petOwners = - { new PetOwner { Name="Higa", - Pets = new List{ - new Pet { Name="Scruffy", Breed="Poodle" }, - new Pet { Name="Sam", Breed="Hound" } } }, - new PetOwner { Name="Ashkenazi", - Pets = new List{ - new Pet { Name="Walker", Breed="Collie" }, - new Pet { Name="Sugar", Breed="Poodle" } } }, - new PetOwner { Name="Price", - Pets = new List{ - new Pet { Name="Scratches", Breed="Dachshund" }, - new Pet { Name="Diesel", Breed="Collie" } } }, - new PetOwner { Name="Hines", - Pets = new List{ - new Pet { Name="Dusty", Breed="Collie" } } } - }; + [ new() { Name="Higa", + Pets = [ + new() { Name="Scruffy", Breed="Poodle" }, + new() { Name="Sam", Breed="Hound" } ] }, + new() { Name="Ashkenazi", + Pets = [ + new() { Name="Walker", Breed="Collie" }, + new() { Name="Sugar", Breed="Poodle" } ] }, + new() { Name="Price", + Pets = [ + new() { Name="Scratches", Breed="Dachshund" }, + new() { Name="Diesel", Breed="Collie" } ] }, + new() { Name="Hines", + Pets = [ + new() { Name="Dusty", Breed="Collie" } ] } + ]; // This query demonstrates how to obtain a sequence of // the names of all the pets whose breed is "Collie", while @@ -1992,12 +1996,12 @@ class Pet public static void SequenceEqualEx1() { - Pet pet1 = new Pet { Name = "Turbo", Age = 2 }; - Pet pet2 = new Pet { Name = "Peanut", Age = 8 }; + Pet pet1 = new() { Name = "Turbo", Age = 2 }; + Pet pet2 = new() { Name = "Peanut", Age = 8 }; // Create two lists of pets. - List pets1 = new List { pet1, pet2 }; - List pets2 = new List { pet1, pet2 }; + List pets1 = [pet1, pet2]; + List pets2 = [pet1, pet2]; // Determine if the lists are equal. bool equal = pets1.AsQueryable().SequenceEqual(pets2); @@ -2027,15 +2031,16 @@ class Pet public static void SequenceEqualEx2() { - Pet pet1 = new Pet() { Name = "Turbo", Age = 2 }; - Pet pet2 = new Pet() { Name = "Peanut", Age = 8 }; + Pet pet1 = new() { Name = "Turbo", Age = 2 }; + Pet pet2 = new() { Name = "Peanut", Age = 8 }; // Create two lists of pets. - List pets1 = new List { pet1, pet2 }; - List pets2 = new List { + List pets1 = [pet1, pet2]; + List pets2 = + [ new Pet { Name = "Turbo", Age = 2 }, new Pet { Name = "Peanut", Age = 8 } - }; + ]; // Determine if the lists are equal. bool equal = pets1.AsQueryable().SequenceEqual(pets2); @@ -2058,8 +2063,8 @@ static void SingleEx1() { // // Create two arrays. - string[] fruits1 = { "orange" }; - string[] fruits2 = { "orange", "apple" }; + string[] fruits1 = ["orange"]; + string[] fruits2 = ["orange", "apple"]; // Get the only item in the first array. string fruit1 = fruits1.AsQueryable().Single(); @@ -2095,11 +2100,12 @@ static void SingleEx1() static void SingleEx2() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; // Get the only string in the array whose length is greater than 10. - string fruit1 = fruits.AsQueryable().Single(fruit => fruit.Length > 10); + string fruit1 = fruits.AsQueryable() + .Single(fruit => fruit.Length > 10); Console.WriteLine("First Query: " + fruit1); @@ -2107,7 +2113,8 @@ static void SingleEx2() { // Try to get the only string in the array // whose length is greater than 15. - string fruit2 = fruits.AsQueryable().Single(fruit => fruit.Length > 15); + string fruit2 = fruits.AsQueryable() + .Single(fruit => fruit.Length > 15); Console.WriteLine("Second Query: " + fruit2); } catch (System.InvalidOperationException) @@ -2133,8 +2140,8 @@ static void SingleOrDefaultEx1() { // // Create two arrays. The second is empty. - string[] fruits1 = { "orange" }; - string[] fruits2 = { }; + string[] fruits1 = ["orange"]; + string[] fruits2 = []; // Get the only item in the first array, or else // the default value for type string (null). @@ -2145,7 +2152,7 @@ static void SingleOrDefaultEx1() // the default value for type string (null). string fruit2 = fruits2.AsQueryable().SingleOrDefault(); Console.WriteLine("Second Query: " + - (String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2)); + (string.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2)); /* This code produces the following output: @@ -2160,21 +2167,21 @@ static void SingleOrDefaultEx1() static void SingleOrDefaultEx2() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; // Get the single string in the array whose length is greater // than 10, or else the default value for type string (null). - string fruit1 = - fruits.AsQueryable().SingleOrDefault(fruit => fruit.Length > 10); + string fruit1 = fruits.AsQueryable() + .SingleOrDefault(fruit => fruit.Length > 10); Console.WriteLine("First Query: " + fruit1); // Get the single string in the array whose length is greater // than 15, or else the default value for type string (null). - string fruit2 = - fruits.AsQueryable().SingleOrDefault(fruit => fruit.Length > 15); + string fruit2 = fruits.AsQueryable() + .SingleOrDefault(fruit => fruit.Length > 15); Console.WriteLine("Second Query: " + - (String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2)); + (string.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2)); /* This code produces the following output: @@ -2189,7 +2196,7 @@ static void SingleOrDefaultEx2() static void SingleOrDefaultEx3() { // - int[] pageNumbers = { }; + int[] pageNumbers = []; // Setting the default value to 1 after the query. int pageNumber1 = pageNumbers.AsQueryable().SingleOrDefault(); @@ -2218,12 +2225,12 @@ The value of the pageNumber2 variable is 1 static void SkipEx1() { // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; // Sort the grades in descending order and // get all except the first three. - IEnumerable lowerGrades = - grades.AsQueryable().OrderByDescending(g => g).Skip(3); + IEnumerable lowerGrades = grades.AsQueryable() + .OrderByDescending(g => g).Skip(3); Console.WriteLine("All grades except the top three are:"); foreach (int grade in lowerGrades) @@ -2247,7 +2254,7 @@ static void SkipEx1() static void SkipWhileEx1() { // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; // Get all grades less than 80 by first // sorting the grades in descending order and then @@ -2277,8 +2284,8 @@ static void SkipWhileEx1() static void SkipWhileEx2() { // - int[] amounts = { 5000, 2500, 9000, 8000, - 6500, 4000, 1500, 5500 }; + int[] amounts = [ 5000, 2500, 9000, 8000, + 6500, 4000, 1500, 5500 ]; // Skip over amounts in the array until the first amount // that is less than or equal to the product of its @@ -2306,7 +2313,7 @@ static void SkipWhileEx2() static void SumEx1() { // - List numbers = new List { 43.68F, 1.25F, 583.7F, 6.5F }; + List numbers = [43.68F, 1.25F, 583.7F, 6.5F]; float sum = numbers.AsQueryable().Sum(); @@ -2324,7 +2331,7 @@ The sum of the numbers is 635.13. static void SumEx2() { // - float?[] points = { null, 0, 92.83F, null, 100.0F, 37.46F, 81.1F }; + float?[] points = [null, 0, 92.83F, null, 100.0F, 37.46F, 81.1F]; float? sum = points.AsQueryable().Sum(); @@ -2351,14 +2358,14 @@ class Package public static void SumEx3() { List packages = - new List - { new Package { Company = "Coho Vineyard", Weight = 25.2 }, + [ new Package { Company = "Coho Vineyard", Weight = 25.2 }, new Package { Company = "Lucerne Publishing", Weight = 18.7 }, new Package { Company = "Wingtip Toys", Weight = 6.0 }, - new Package { Company = "Adventure Works", Weight = 33.8 } }; + new Package { Company = "Adventure Works", Weight = 33.8 } ]; // Calculate the sum of all package weights. - double totalWeight = packages.AsQueryable().Sum(pkg => pkg.Weight); + double totalWeight = packages.AsQueryable() + .Sum(pkg => pkg.Weight); Console.WriteLine("The total weight of the packages is: {0}", totalWeight); } @@ -2377,11 +2384,11 @@ public static void SumEx3() static void TakeEx1() { // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; // Sort the grades in descending order and take the first three. - IEnumerable topThreeGrades = - grades.AsQueryable().OrderByDescending(grade => grade).Take(3); + IEnumerable topThreeGrades = grades.AsQueryable() + .OrderByDescending(grade => grade).Take(3); Console.WriteLine("The top three grades are:"); foreach (int grade in topThreeGrades) @@ -2404,14 +2411,14 @@ static void TakeEx1() static void TakeWhileEx1() { // - string[] fruits = { "apple", "banana", "mango", "orange", - "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", "orange", + "passionfruit", "grape" ]; // Take strings from the array until a string // that is equal to "orange" is found. IEnumerable query = fruits.AsQueryable() - .TakeWhile(fruit => String.Compare("orange", fruit, true) != 0); + .TakeWhile(fruit => string.Compare("orange", fruit, true) != 0); foreach (string fruit in query) Console.WriteLine(fruit); @@ -2430,8 +2437,8 @@ static void TakeWhileEx1() static void TakeWhileEx2() { // - string[] fruits = { "apple", "passionfruit", "banana", "mango", - "orange", "blueberry", "grape", "strawberry" }; + string[] fruits = [ "apple", "passionfruit", "banana", "mango", + "orange", "blueberry", "grape", "strawberry" ]; // Take strings from the array until a string whose length // is less than its index in the array is found. @@ -2461,14 +2468,14 @@ static void TakeWhileEx2() static void ThenByEx1() { // - string[] fruits = { "grape", "passionfruit", "banana", "apple", - "orange", "raspberry", "mango", "blueberry" }; + string[] fruits = [ "grape", "passionfruit", "banana", "apple", + "orange", "raspberry", "mango", "blueberry" ]; // Sort the strings first by their length and then // alphabetically by passing the identity selector function. - IEnumerable query = - fruits.AsQueryable() - .OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit); + IEnumerable query = fruits.AsQueryable() + .OrderBy(fruit => fruit.Length) + .ThenBy(fruit => fruit); foreach (string fruit in query) Console.WriteLine(fruit); @@ -2494,25 +2501,17 @@ static void ThenByEx1() static class ThenByDescending { // - public class CaseInsensitiveComparer : IComparer - { - public int Compare(string x, string y) - { - return string.Compare(x, y, true); - } - } - public static void ThenByDescendingEx1() { string[] fruits = - { "apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE" }; + ["apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE"]; // Sort the strings first ascending by their length and // then descending using a custom case insensitive comparer. IEnumerable query = fruits.AsQueryable() .OrderBy(fruit => fruit.Length) - .ThenByDescending(fruit => fruit, new CaseInsensitiveComparer()); + .ThenByDescending(fruit => fruit, StringComparer.OrdinalIgnoreCase); foreach (string fruit in query) Console.WriteLine(fruit); @@ -2539,8 +2538,8 @@ public static void ThenByDescendingEx1() static void UnionEx1() { // - int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 }; - int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 }; + int[] ints1 = [5, 3, 9, 7, 5, 9, 3, 7]; + int[] ints2 = [8, 3, 6, 4, 4, 9, 1, 0]; // Get the set union of the items in the two arrays. IEnumerable union = ints1.AsQueryable().Union(ints2); @@ -2565,12 +2564,12 @@ static void WhereEx1() { // List fruits = - new List { "apple", "passionfruit", "banana", "mango", - "orange", "blueberry", "grape", "strawberry" }; + [ "apple", "passionfruit", "banana", "mango", + "orange", "blueberry", "grape", "strawberry" ]; // Get all strings whose length is less than 6. - IEnumerable query = - fruits.AsQueryable().Where(fruit => fruit.Length < 6); + IEnumerable query = fruits.AsQueryable() + .Where(fruit => fruit.Length < 6); foreach (string fruit in query) Console.WriteLine(fruit); @@ -2589,7 +2588,7 @@ static void WhereEx1() static void WhereEx2() { // - int[] numbers = { 0, 30, 20, 15, 90, 85, 40, 75 }; + int[] numbers = [0, 30, 20, 15, 90, 85, 40, 75]; // Get all the numbers that are less than or equal to // the product of their index in the array and 10. @@ -2617,12 +2616,13 @@ static void WhereEx2() static void ZipEx() { // - int[] numbers = { 1, 2, 3, 4 }; - string[] words = { "one", "two", "three" }; + int[] numbers = [1, 2, 3, 4]; + string[] words = ["one", "two", "three"]; - var numbersAndWords = numbers.AsQueryable().Zip(words, (first, second) => first + " " + second); + IQueryable numbersAndWords = numbers.AsQueryable() + .Zip(words, (first, second) => first + " " + second); - foreach (var item in numbersAndWords) + foreach (string item in numbersAndWords) Console.WriteLine(item); // This code produces the following output: From 6dd3e2caf628b8718a162f655fd97bed222c16de Mon Sep 17 00:00:00 2001 From: DickBaker Date: Thu, 11 Jul 2024 15:36:12 +0100 Subject: [PATCH 2/8] COB711 --- .../System.Linq/Enumerable/AggregateTSource/enumerable.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs index caa6c5709a6..48e833d818d 100644 --- a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs +++ b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs @@ -238,7 +238,7 @@ public static void AnyEx3() new Pet { Name="Boots", Age=4, Vaccinated=false }, new Pet { Name="Whiskers", Age=1, Vaccinated=false } ]; - // Determine whether any pets over age 1 are also unvaccinated. + // Determine whether any pets over _age 1 are also unvaccinated. bool unvaccinated = pets.Any(p => p.Age > 1 && !p.Vaccinated); @@ -964,7 +964,7 @@ public static void GroupByEx2() new Pet { Name="Daisy", Age=4 } ]; // Group the pets using Age as the key value - // and selecting only the pet's Name for each value. + // and selecting only the pet's name for each value. // IEnumerable> query = from pet in pets From 86b1286b3bcbf66b601a16bc72071d2212a7bd76 Mon Sep 17 00:00:00 2001 From: DickBaker Date: Sun, 14 Jul 2024 22:27:58 +0100 Subject: [PATCH 3/8] COB714 --- snippets/csharp/System.Linq/.editorconfig | 82 +- .../AggregateTSource/Enumerable.csproj | 3 +- .../Enumerable/AggregateTSource/enumerable.cs | 721 +++++++++--------- .../Enumerable/Comparers/Comparers.csproj | 1 + .../Enumerable/Comparers/CustomComparer.cs | 80 +- .../Comparers/EncapsulatedComparer.cs | 73 +- .../Overview/IGrouping.csproj | 5 +- .../Overview/igrouping.cs | 23 +- .../ILookupTKey,TElement/Overview/ILookup.cs | 21 +- .../Overview/ILookup.csproj | 5 +- .../Overview/IOrderedEnumerable.cs | 5 +- .../Overview/IOrderedEnumerable.csproj | 5 +- .../AggregateTSource/AggregateTSource.csproj | 3 +- .../Queryable/AggregateTSource/queryable.cs | 385 ++++++---- snippets/csharp/System.Linq/README.txt | 9 + 15 files changed, 766 insertions(+), 655 deletions(-) create mode 100644 snippets/csharp/System.Linq/README.txt diff --git a/snippets/csharp/System.Linq/.editorconfig b/snippets/csharp/System.Linq/.editorconfig index 336d6ecabe3..7910af9eb54 100644 --- a/snippets/csharp/System.Linq/.editorconfig +++ b/snippets/csharp/System.Linq/.editorconfig @@ -82,32 +82,32 @@ csharp_style_var_for_built_in_types = true:silent csharp_style_var_when_type_is_apparent = true:silent # Expression-bodied members -csharp_style_expression_bodied_accessors = true:silent -csharp_style_expression_bodied_constructors = true:silent -csharp_style_expression_bodied_indexers = true +csharp_style_expression_bodied_accessors = true:suggestion +csharp_style_expression_bodied_constructors = true:suggestion +csharp_style_expression_bodied_indexers = true:suggestion csharp_style_expression_bodied_lambdas = true:suggestion csharp_style_expression_bodied_local_functions = true:suggestion -csharp_style_expression_bodied_methods = true:silent -csharp_style_expression_bodied_operators = true:silent -csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_methods = true:suggestion +csharp_style_expression_bodied_operators = true:suggestion +csharp_style_expression_bodied_properties = true:suggestion # Pattern matching preferences -csharp_style_pattern_matching_over_as_with_null_check = true -csharp_style_pattern_matching_over_is_with_cast_check = true -csharp_style_prefer_extended_property_pattern = true -csharp_style_prefer_not_pattern = true -csharp_style_prefer_pattern_matching = true -csharp_style_prefer_switch_expression = true +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_prefer_extended_property_pattern = true:suggestion +csharp_style_prefer_not_pattern = true:suggestion +csharp_style_prefer_pattern_matching = true:suggestion +csharp_style_prefer_switch_expression = true:suggestion # Null-checking preferences -csharp_style_conditional_delegate_call = true +csharp_style_conditional_delegate_call = true:suggestion # Modifier preferences -csharp_prefer_static_anonymous_function = true -csharp_prefer_static_local_function = true +csharp_prefer_static_anonymous_function = true:suggestion +csharp_prefer_static_local_function = true:suggestion csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async -csharp_style_prefer_readonly_struct = true -csharp_style_prefer_readonly_struct_member = true +csharp_style_prefer_readonly_struct = true:suggestion +csharp_style_prefer_readonly_struct_member = true:suggestion # Code-block preferences csharp_prefer_braces = true:silent @@ -118,29 +118,29 @@ csharp_style_prefer_primary_constructors = true:suggestion csharp_style_prefer_top_level_statements = true:silent # Expression-level preferences -csharp_prefer_simple_default_expression = true +csharp_prefer_simple_default_expression = true:suggestion csharp_style_deconstructed_variable_declaration = true:suggestion csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion csharp_style_inlined_variable_declaration = true:suggestion -csharp_style_prefer_index_operator = true -csharp_style_prefer_local_over_anonymous_function = true -csharp_style_prefer_null_check_over_type_check = true -csharp_style_prefer_range_operator = true -csharp_style_prefer_tuple_swap = true -csharp_style_prefer_utf8_string_literals = true -csharp_style_throw_expression = true +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_local_over_anonymous_function = true:suggestion +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_prefer_tuple_swap = true:suggestion +csharp_style_prefer_utf8_string_literals = true:suggestion +csharp_style_throw_expression = true:suggestion csharp_style_unused_value_assignment_preference = discard_variable:silent -csharp_style_unused_value_expression_statement_preference = discard_variable +csharp_style_unused_value_expression_statement_preference = discard_variable:silent # 'using' directive preferences csharp_using_directive_placement = outside_namespace:suggestion # New line preferences -csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false -csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true -csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false:silent +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false:silent -csharp_style_allow_embedded_statements_on_same_line_experimental = true +csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent #### C# Formatting Rules #### @@ -246,4 +246,24 @@ dotnet_style_qualification_for_event = false:silent dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:silent dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:silent dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:silent -dotnet_style_parentheses_in_other_operators = always_for_clarity:silent \ No newline at end of file +dotnet_style_parentheses_in_other_operators = always_for_clarity:silent +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:warning +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion +dotnet_style_readonly_field = true:suggestion +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_allow_multiple_blank_lines_experimental = false:silent +dotnet_style_allow_statement_immediately_after_block_experimental = true:silent +dotnet_code_quality_unused_parameters = all:suggestion \ No newline at end of file diff --git a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj index ff1021b1134..c5d80d0822a 100644 --- a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj +++ b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj @@ -1,8 +1,9 @@ - + Exe net8.0 + enable diff --git a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs index 48e833d818d..3cfc3c64acd 100644 --- a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs +++ b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs @@ -74,23 +74,22 @@ static void AggregateEx3() static class All { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void AllEx() { // Create an array of Pets. - Pet[] pets = [ new Pet { Name="Barley", Age=10 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=6 } ]; + Pet[] pets = [ new ("Barley", 10 ), + new ("Boots", 4 ), + new ("Whiskers", 6 ) ]; // Determine whether all pet names // in the array start with 'B'. - bool allStartWithB = pets.All(pet => - pet.Name.StartsWith('B')); + bool allStartWithB = pets.All(pet => pet.Name.StartsWith('B')); Console.WriteLine( "{0} pet names start with 'B'.", @@ -106,31 +105,31 @@ public static void AllEx() static class All2 { // - class Pet + class Pet (string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } - class Person + class Person(string lastName, Pet[] pets) { - public string LastName { get; set; } - public Pet[] Pets { get; set; } + public string LastName { get; set; } = lastName; + public Pet[] Pets { get; set; } = pets; } public static void AllEx2() { List people = - [ new Person { LastName = "Haas", - Pets = [ new Pet { Name="Barley", Age=10 }, - new Pet { Name="Boots", Age=14 }, - new Pet { Name="Whiskers", Age=6 }]}, - new Person { LastName = "Fakhouri", - Pets = [new Pet { Name = "Snowball", Age = 1}]}, - new Person { LastName = "Antebi", - Pets = [new Pet { Name = "Belle", Age = 8}]}, - new Person { LastName = "Philips", - Pets = [ new Pet { Name = "Sweetie", Age = 2}, - new Pet { Name = "Rover", Age = 13}] } + [ new Person ("Haas", + [ new ("Barley", 10 ), + new ("Boots", 14 ), + new ("Whiskers", 6 )]), + new Person ("Fakhouri", + [new ("Snowball", 1)]), + new Person ("Antebi", + [new ("Belle", 8)]), + new Person ("Philips", + [ new ("Sweetie", 2), + new ("Rover", 13)] ) ]; // Determine which people have pets that are all older than 5. @@ -173,31 +172,31 @@ public static void AnyEx1() } // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } - class Person + class Person(string lastName, Pet[] pets) { - public string LastName { get; set; } - public Pet[] Pets { get; set; } + public string LastName { get; set; } = lastName; + public Pet[] Pets { get; set; } = pets; } public static void AnyEx2() { List people = - [ new Person { LastName = "Haas", - Pets = [ new Pet { Name="Barley", Age=10 }, - new Pet { Name="Boots", Age=14 }, - new Pet { Name="Whiskers", Age=6 }]}, - new Person { LastName = "Fakhouri", - Pets = [new Pet { Name = "Snowball", Age = 1}]}, - new Person { LastName = "Antebi", - Pets = []}, - new Person { LastName = "Philips", - Pets = [ new Pet { Name = "Sweetie", Age = 2}, - new Pet { Name = "Rover", Age = 13}] } + [ new Person ("Haas", + [ new ("Barley", 10 ), + new ("Boots", 14 ), + new ("Whiskers", 6 )]), + new Person ("Fakhouri", + [new ("Snowball", 1)]), + new Person ("Antebi", + []), + new Person ("Philips", + [ new ("Sweetie", 2), + new ("Rover", 13)] ) ]; // Determine which people have a non-empty Pet array. @@ -223,22 +222,22 @@ public static void AnyEx2() static class Any2 { // - class Pet + class Pet(string name, int age, bool vaccinated) { - public string Name { get; set; } - public int Age { get; set; } - public bool Vaccinated { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; + public bool Vaccinated { get; set; } = vaccinated; } public static void AnyEx3() { // Create an array of Pets. Pet[] pets = - [ new Pet { Name="Barley", Age=8, Vaccinated=true }, - new Pet { Name="Boots", Age=4, Vaccinated=false }, - new Pet { Name="Whiskers", Age=1, Vaccinated=false } ]; + [ new ("Barley", 8, true ), + new ("Boots", 4, false ), + new ("Whiskers", 1, false ) ]; - // Determine whether any pets over _age 1 are also unvaccinated. + // Determine whether any pets over age 1 are also unvaccinated. bool unvaccinated = pets.Any(p => p.Age > 1 && !p.Vaccinated); @@ -338,7 +337,7 @@ static void AverageEx3() // string[] numbers = ["10007", "37", "299846234235"]; - double average = numbers.Average(num => long.Parse(num)); + double average = numbers.Average(long.Parse); Console.WriteLine("The average is {0}.", average); @@ -370,12 +369,12 @@ static void CastEx1() // System.Collections.ArrayList fruits = ["mango", "apple", "lemon"]; - IEnumerable query = - fruits.Cast().OrderBy(fruit => fruit).Select(fruit => fruit); + IEnumerable query = fruits.Cast() + .OrderBy(fruit => fruit) + .Select(fruit => fruit); - // The following code, without the cast, doesn't compile. - //IEnumerable query1 = - // fruits.OrderBy(fruit => fruit).Select(fruit => fruit); + //The following code, without the cast, doesn't compile (no System.Linq.Enumerable.OrderBy extension method for ArrayList) + //var query1 = fruits.OrderBy(fruit => fruit).Select(fruit => fruit); foreach (string fruit in query) { @@ -395,25 +394,25 @@ static void CastEx1() static class Concat { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } static Pet[] GetCats() { - Pet[] cats = [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } ]; + Pet[] cats = [ new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; return cats; } static Pet[] GetDogs() { - Pet[] dogs = [ new Pet { Name="Bounder", Age=3 }, - new Pet { Name="Snoopy", Age=14 }, - new Pet { Name="Fido", Age=9 } ]; + Pet[] dogs = [ new ("Bounder", 3 ), + new ("Snoopy", 14 ), + new ("Fido", 9 ) ]; return dogs; } @@ -422,9 +421,9 @@ public static void ConcatEx1() Pet[] cats = GetCats(); Pet[] dogs = GetDogs(); - IEnumerable query = - cats.Select(cat => cat.Name) - .Concat(dogs.Select(dog => dog.Name)); + IEnumerable query = cats + .Select(cat => cat.Name) + .Concat(dogs.Select(dog => dog.Name)); foreach (string name in query) { @@ -448,8 +447,9 @@ public static void ConcatEx2() Pet[] cats = GetCats(); Pet[] dogs = GetDogs(); - IEnumerable query = - new[] { cats.Select(cat => cat.Name), dogs.Select(dog => dog.Name) } + IEnumerable query = new[] + { cats.Select(cat => cat.Name), + dogs.Select(dog => dog.Name) } .SelectMany(name => name); foreach (string name in query) @@ -519,18 +519,18 @@ static void CountEx1() static class Count { - // - class Pet - { - public string Name { get; set; } - public bool Vaccinated { get; set; } - } + // + class Pet(string name, bool vaccinated) + { + public string Name { get; set; } = name; + public bool Vaccinated { get; set; } = vaccinated; + } public static void CountEx2() { - Pet[] pets = [ new Pet { Name="Barley", Vaccinated=true }, - new Pet { Name="Boots", Vaccinated=false }, - new Pet { Name="Whiskers", Vaccinated=false } ]; + Pet[] pets = [ new ("Barley", true ), + new ("Boots", false ), + new ("Whiskers", false ) ]; try { @@ -555,22 +555,22 @@ public static void CountEx2() static class DefaultIfEmpty1 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void DefaultIfEmptyEx1() { List pets = - [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } ]; + [ new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; - foreach (Pet pet in pets.DefaultIfEmpty()) + foreach (var pet in pets.DefaultIfEmpty()) { - Console.WriteLine(pet.Name); + Console.WriteLine(pet?.Name); } } @@ -605,20 +605,20 @@ static void DefaultIfEmptyEx1a() static class DefaultIfEmtpy2 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void DefaultIfEmptyEx2() { - Pet defaultPet = new() { Name = "Default Pet", Age = 0 }; + Pet defaultPet = new("Default Pet", 0); - List pets1 = - [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } ]; + List pets1 = + [ new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; foreach (Pet pet in pets1.DefaultIfEmpty(defaultPet)) { @@ -707,12 +707,13 @@ static void ElementAtOrDefaultEx1() const int index = 20; - string name = names.ElementAtOrDefault(index); + var name = names.ElementAtOrDefault(index); + //var name = names[index]; Console.WriteLine( "The name chosen at index {0} is '{1}'.", index, - string.IsNullOrEmpty(name) ? "" : name); + name ?? ""); /* This code produces the following output: @@ -781,7 +782,9 @@ static void ExceptEx1() IEnumerable onlyInFirstSet = numbers1.Except(numbers2); foreach (double number in onlyInFirstSet) + { Console.WriteLine(number); + } /* This code produces the following output: @@ -857,15 +860,14 @@ static void FirstOrDefaultEx2() "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu" ]; - string firstLongName = names.FirstOrDefault(name => name.Length > 20); + var firstLongName = names.FirstOrDefault(name => name.Length > 20); Console.WriteLine("The first long name is '{0}'.", firstLongName); - string firstVeryLongName = names.FirstOrDefault(name => name.Length > 30); + var firstVeryLongName = names.FirstOrDefault(name => name.Length > 30); - Console.WriteLine( - "There is {0} name longer than 30 characters.", - string.IsNullOrEmpty(firstVeryLongName) ? "not a" : "a"); + Console.WriteLine("There is {0} name longer than 30 characters.", + firstVeryLongName is null ? "not a" : "a"); /* This code produces the following output: @@ -907,10 +909,10 @@ The value of the firstMonth2 variable is 1 static class GroupBy { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } // Uses method-based query syntax. @@ -918,10 +920,10 @@ public static void GroupByEx1() { // Create a list of pets. List pets = - [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 }, - new Pet { Name="Daisy", Age=4 } ]; + [ new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ), + new ("Daisy", 4 ) ]; // Group the pets using Age as the key value // and selecting only the pet's Name for each value. @@ -936,7 +938,9 @@ public static void GroupByEx1() // Iterate over each value in the // IGrouping and print the value. foreach (string name in petGroup) + { Console.WriteLine(" {0}", name); + } } } @@ -958,10 +962,10 @@ public static void GroupByEx2() { // Create a list of pets. List pets = - [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 }, - new Pet { Name="Daisy", Age=4 } ]; + [ new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ), + new ("Daisy", 4 ) ]; // Group the pets using Age as the key value // and selecting only the pet's name for each value. @@ -979,7 +983,9 @@ from pet in pets // Iterate over each value in the IGrouping // and print the value. foreach (string name in petGroup) + { Console.WriteLine(" {0}", name); + } } } } @@ -987,30 +993,30 @@ from pet in pets static class GroupBy3 { // - class Pet + class Pet(string name, float age) { - public string Name { get; set; } - public double Age { get; set; } + public string Name { get; set; } = name; + public float Age { get; set; } = age; } public static void GroupByEx3() { // Create a list of pets. List petsList = - [ new Pet { Name="Barley", Age=8.3 }, - new Pet { Name="Boots", Age=4.9 }, - new Pet { Name="Whiskers", Age=1.5 }, - new Pet { Name="Daisy", Age=4.3 } ]; + [ new ("Barley", 8.3f ), + new ("Boots", 4.9f ), + new ("Whiskers", 1.5f ), + new ("Daisy", 4.3f ) ]; // Group Pet objects by the Math.Floor of their age. // Then project an anonymous type from each group // that consists of the key, the count of the group's // elements, and the minimum and maximum age in the group. var query = petsList.GroupBy( - pet => Math.Floor(pet.Age), - (age, pets) => new + pet => (int)Math.Floor(pet.Age), + (baseAge, pets) => new { - Key = age, + Key = baseAge, Count = pets.Count(), Min = pets.Min(pet => pet.Age), Max = pets.Max(pet => pet.Age) @@ -1050,27 +1056,27 @@ public static void GroupByEx3() static class GroupBy4 { // - class Pet + class Pet(string name, float age) { - public string Name { get; set; } - public double Age { get; set; } + public string Name { get; set; } = name; + public float Age { get; set; } = age; } public static void GroupByEx4() { // Create a list of pets. List petsList = - [ new Pet { Name="Barley", Age=8.3 }, - new Pet { Name="Boots", Age=4.9 }, - new Pet { Name="Whiskers", Age=1.5 }, - new Pet { Name="Daisy", Age=4.3 } ]; + [ new ("Barley", 8.3f ), + new ("Boots", 4.9f ), + new ("Whiskers", 1.5f ), + new ("Daisy", 4.3f ) ]; // Group Pet.Age values by the Math.Floor of the age. // Then project an anonymous type from each group // that consists of the key, the count of the group's // elements, and the minimum and maximum age in the group. var query = petsList.GroupBy( - pet => Math.Floor(pet.Age), + pet => (int)Math.Floor(pet.Age), pet => pet.Age, (baseAge, ages) => new { @@ -1115,27 +1121,27 @@ public static void GroupByEx4() static class GroupJoin { // - class Person + class Person(string name) { - public string Name { get; set; } + public string Name { get; set; } = name; } - class Pet + class Pet(string name, Person owner) { - public string Name { get; set; } - public Person Owner { get; set; } + public string Name { get; set; } = name; + public Person Owner { get; set; } = owner; } public static void GroupJoinEx1() { - Person magnus = new() { Name = "Hedlund, Magnus" }; - Person terry = new() { Name = "Adams, Terry" }; - Person charlotte = new() { Name = "Weiss, Charlotte" }; + Person magnus = new("Hedlund, Magnus" ); + Person terry = new("Adams, Terry" ); + Person charlotte = new("Weiss, Charlotte" ); - Pet barley = new() { Name = "Barley", Owner = terry }; - Pet boots = new() { Name = "Boots", Owner = terry }; - Pet whiskers = new() { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new() { Name = "Daisy", Owner = magnus }; + Pet barley = new("Barley", terry ); + Pet boots = new("Boots", terry ); + Pet whiskers = new("Whiskers", charlotte ); + Pet daisy = new("Daisy", magnus ); List people = [magnus, terry, charlotte]; List pets = [barley, boots, whiskers, daisy]; @@ -1182,27 +1188,28 @@ public static void GroupJoinEx1() // Uses query syntax. public static void GroupJoinEx2() { - Person magnus = new() { Name = "Hedlund, Magnus" }; - Person terry = new() { Name = "Adams, Terry" }; - Person charlotte = new() { Name = "Weiss, Charlotte" }; + Person magnus = new("Hedlund, Magnus" ); + Person terry = new("Adams, Terry" ); + Person charlotte = new("Weiss, Charlotte" ); - Pet barley = new() { Name = "Barley", Owner = terry }; - Pet boots = new() { Name = "Boots", Owner = terry }; - Pet whiskers = new() { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new() { Name = "Daisy", Owner = magnus }; + Pet barley = new("Barley", terry ); + Pet boots = new("Boots", terry ); + Pet whiskers = new("Whiskers", charlotte ); + Pet daisy = new("Daisy", magnus ); List people = [magnus, terry, charlotte]; List pets = [barley, boots, whiskers, daisy]; // - var query = from person in people - join pet in pets - on person equals pet.Owner into petCollection - select new - { - OwnerName = person.Name, - Pets = petCollection.Select(p => p.Name) - }; + var query = + from person in people + join pet in pets + on person equals pet.Owner into petCollection + select new + { + OwnerName = person.Name, + Pets = petCollection.Select(p => p.Name) + }; // foreach (var obj in query) @@ -1229,7 +1236,9 @@ static void IntersectEx1() IEnumerable both = id1.Intersect(id2); foreach (int id in both) + { Console.WriteLine(id); + } /* This code produces the following output: @@ -1245,27 +1254,27 @@ static void IntersectEx1() static class Join { // - class Person + class Person(string name) { - public string Name { get; set; } + public string Name { get; set; } = name; } - class Pet + class Pet(string name, Person owner) { - public string Name { get; set; } - public Person Owner { get; set; } + public string Name { get; set; } = name; + public Person Owner { get; set; } = owner; } public static void JoinEx1() { - Person magnus = new() { Name = "Hedlund, Magnus" }; - Person terry = new() { Name = "Adams, Terry" }; - Person charlotte = new() { Name = "Weiss, Charlotte" }; + Person magnus = new ("Hedlund, Magnus" ); + Person terry = new("Adams, Terry" ); + Person charlotte = new("Weiss, Charlotte" ); - Pet barley = new() { Name = "Barley", Owner = terry }; - Pet boots = new() { Name = "Boots", Owner = terry }; - Pet whiskers = new() { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new() { Name = "Daisy", Owner = magnus }; + Pet barley = new("Barley", terry ); + Pet boots = new("Boots", terry ); + Pet whiskers = new("Whiskers", charlotte ); + Pet daisy = new("Daisy", magnus ); List people = [magnus, terry, charlotte]; List pets = [barley, boots, whiskers, daisy]; @@ -1344,9 +1353,8 @@ static void LastOrDefaultEx1() { // string[] fruits = []; - string last = fruits.LastOrDefault(); - Console.WriteLine( - string.IsNullOrEmpty(last) ? "" : last); + var last = fruits.LastOrDefault(); + Console.WriteLine(last ?? ""); /* This code produces the following output: @@ -1429,17 +1437,17 @@ There are 6 fruits in the collection. static class LongCount { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void LongCountEx2() { - Pet[] pets = [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } ]; + Pet[] pets = [ new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; const int Age = 3; @@ -1463,7 +1471,7 @@ static void MaxEx1() // List longs = [4294967296L, 466855135L, 81125L]; - long max = longs.Max(); + var max = longs.Max(); Console.WriteLine("The largest number is {0}.", max); @@ -1480,7 +1488,7 @@ static void MaxEx2() // double?[] doubles = [null, 1.5E+104, 9E+103, -2E+103]; - double? max = doubles.Max(); + var max = doubles.Max(); Console.WriteLine("The largest number is {0}.", max); @@ -1499,10 +1507,11 @@ static class Max2 // IEnumerable /// This class implements IComparable to be able to /// compare one Pet to another Pet. /// - class Pet : IComparable + public class Pet(string name, int? age) : IComparable { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; } = name; + + public int Age { get; } = age ?? 0; /// /// Compares this Pet to another Pet by @@ -1512,37 +1521,41 @@ class Pet : IComparable /// -1 if this Pet is 'less' than the other Pet, /// 0 if they are equal, /// or 1 if this Pet is 'greater' than the other Pet. - int IComparable.CompareTo(Pet other) + public int CompareTo(Pet? other) { + if (other is null) return -1; int sumOther = other.Age + other.Name.Length; int sumThis = Age + Name.Length; - if (sumOther > sumThis) - return -1; - else if (sumOther == sumThis) - return 0; - else - return 1; + return (sumOther > sumThis) + ? -1 + : (sumOther == sumThis) + ? 0 : 1; } } public static void MaxEx3() { - Pet[] pets = [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } ]; + Pet[] pets = [ new ("Barley", age:8 ), + new ("Boots", age:4 ), + new ("Whiskers", age:1 ) ]; - Pet max = pets.Max(); + //if (pets.Length > 0) + { + var maxage = pets.Max(p => p.Age); + var oldest = pets.First(p => p.Age == maxage); + var oldest2 = pets.OrderByDescending(p => p.Age) + .ThenBy(p => p.Name).First(); - Console.WriteLine( - "The 'maximum' animal is {0}.", - max.Name); + Console.WriteLine("The oldest animal is {0} at {1} years old.", + oldest, oldest.Age); + } } /* This code produces the following output: - The 'maximum' animal is Barley. + The oldest animal is Barley at 8 years old. */ // } @@ -1550,17 +1563,17 @@ public static void MaxEx3() static class Max10 // with a selector { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void MaxEx4() { - Pet[] pets = [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } ]; + Pet[] pets = [ new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; int max = pets.Max(pet => pet.Age + pet.Name.Length); @@ -1585,7 +1598,7 @@ static void MinEx1() // double[] doubles = [1.5E+104, 9E+103, -2E+103]; - double min = doubles.Min(); + var min = doubles.Min(); Console.WriteLine("The smallest number is {0}.", min); @@ -1602,7 +1615,7 @@ static void MinEx2() // int?[] grades = [78, 92, null, 99, 37, 81]; - int? min = grades.Min(); + var min = grades.Min(); Console.WriteLine("The lowest grade is {0}.", min); @@ -1621,10 +1634,10 @@ static class Min9 // IEnumerable /// This class implements IComparable in order to /// be able to compare different Pet objects. /// - class Pet : IComparable + class Pet (string name , int age): IComparable { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; /// /// Compares this Pet's age to another Pet's age. @@ -1633,34 +1646,31 @@ class Pet : IComparable /// -1 if this Pet's age is smaller, /// 0 if the Pets' ages are equal, or /// 1 if this Pet's age is greater. - int IComparable.CompareTo(Pet other) - { - if (other.Age > Age) - return -1; - else if (other.Age == Age) - return 0; - else - return 1; - } + public int CompareTo(Pet? other) => + (other is null || other.Age > Age) + ? -1 + : (other.Age == Age) + ? 0 : 1; } public static void MinEx3() { - Pet[] pets = [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } ]; + Pet[] pets = [ new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; - Pet min = pets.Min(); + var min = pets.Min(p => p.Age); + var youngest = pets.First(p => p.Age == min); + //var youngest2 = pets.OrderByDescending(p => p.Age).ThenBy(p => p.Name).FirstOrDefault(); - Console.WriteLine( - "The 'minimum' animal is {0}.", - min.Name); + Console.WriteLine("The youngest animal is {0} at {1} years old.", + youngest.Name, youngest.Age); } /* This code produces the following output: - The 'minimum' animal is Whiskers. + The youngest animal is Whiskers at 1 years old. */ // } @@ -1668,19 +1678,19 @@ public static void MinEx3() static class Min10 // with a selector { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void MinEx4() { - Pet[] pets = [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } ]; + Pet[] pets = [ new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; - int min = pets.Min(pet => pet.Age); + var min = pets.Min(pet => pet.Age); Console.WriteLine("The youngest animal is age {0}.", min); } @@ -1721,7 +1731,7 @@ static void OfTypeEx1() // Where() can be applied to the ArrayList type after calling OfType(). IEnumerable query2 = fruits.OfType().Where(fruit => - fruit.Contains('n', StringComparison.CurrentCultureIgnoreCase)); + fruit.Contains('n', StringComparison.CurrentCultureIgnoreCase)); Console.WriteLine("\nThe following strings contain 'n':"); foreach (string fruit in query2) @@ -1749,17 +1759,17 @@ static void OfTypeEx1() static class OrderBy { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void OrderByEx1() { - Pet[] pets = [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } ]; + Pet[] pets = [ new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; IEnumerable query = pets.OrderBy(pet => pet.Age); @@ -1801,7 +1811,7 @@ public static void OrderByIComparer() } // Change the lambda expression to sort by the length of each string. - sortedArray = unsortedArray.OrderBy(a => (a.Length).ToString(), StringComparer.OrdinalIgnoreCase); + sortedArray = unsortedArray.OrderBy(a => a.Length); Console.WriteLine("\nSort based on the lengths of the strings in the array:"); foreach (string element in sortedArray) { @@ -1879,12 +1889,10 @@ public int Compare(decimal d1, decimal d2) fractional2 = d2; } - if (fractional1 == fractional2) - return decimal.Compare(d1, d2); - else if (fractional1 > fractional2) - return 1; - else - return -1; + return (fractional1 == fractional2) + ? decimal.Compare(d1, d2) + : (fractional1 > fractional2) + ? 1 : -1; } } @@ -2042,7 +2050,7 @@ static void SelectEx2() var query = fruits.Select((fruit, index) => - new { index, str = fruit.Substring(0, index) }); + new { index, str = fruit[..index] }); foreach (var obj in query) { @@ -2067,21 +2075,21 @@ static void SelectEx2() static class SelectMany1 { // - class PetOwner + class PetOwner(string name, List pets) { - public string Name { get; set; } - public List Pets { get; set; } + public string Name { get; set; } = name; + public List Pets { get; set; } = pets; } public static void SelectManyEx1() { PetOwner[] petOwners = - [ new PetOwner { Name="Higa, Sidney", - Pets = ["Scruffy", "Sam"] }, - new PetOwner { Name="Ashkenazi, Ronen", - Pets = ["Walker", "Sugar"] }, - new PetOwner { Name="Price, Vernette", - Pets = ["Scratches", "Diesel"] } ]; + [ new ("Higa, Sidney", + ["Scruffy", "Sam"] ), + new ("Ashkenazi, Ronen", + ["Walker", "Sugar"] ), + new ("Price, Vernette", + ["Scratches", "Diesel"] ) ]; // Query using SelectMany(). IEnumerable query1 = petOwners.SelectMany(petOwner => petOwner.Pets); @@ -2143,23 +2151,23 @@ Using Select(): static class SelectMany2 { // - class PetOwner + class PetOwner(string name, List pets) { - public string Name { get; set; } - public List Pets { get; set; } + public string Name { get; set; } = name; + public List Pets { get; set; } = pets; } public static void SelectManyEx2() { PetOwner[] petOwners = - [ new PetOwner { Name="Higa, Sidney", - Pets = ["Scruffy", "Sam"] }, - new PetOwner { Name="Ashkenazi, Ronen", - Pets = ["Walker", "Sugar"] }, - new PetOwner { Name="Price, Vernette", - Pets = ["Scratches", "Diesel"] }, - new PetOwner { Name="Hines, Patrick", - Pets = ["Dusty"] } ]; + [ new ("Higa, Sidney", + ["Scruffy", "Sam"] ), + new ("Ashkenazi, Ronen", + ["Walker", "Sugar"] ), + new ("Price, Vernette", + ["Scratches", "Diesel"] ), + new ("Hines, Patrick", + ["Dusty"] ) ]; // Project the items in the array by appending the index // of each PetOwner to each pet's name in that petOwner's @@ -2189,27 +2197,26 @@ public static void SelectManyEx2() static class SelectMany3 { // - class PetOwner + class PetOwner(string name, List pets) { - public string Name { get; set; } - public List Pets { get; set; } + public string Name { get; set; } = name; + public List Pets { get; set; } = pets; } public static void SelectManyEx3() { PetOwner[] petOwners = - [ new PetOwner { Name="Higa", - Pets = ["Scruffy", "Sam"] }, - new PetOwner { Name="Ashkenazi", - Pets = ["Walker", "Sugar"] }, - new PetOwner { Name="Price", - Pets = ["Scratches", "Diesel"] }, - new PetOwner { Name="Hines", - Pets = ["Dusty"] } ]; + [ new ("Higa", + ["Scruffy", "Sam"] ), + new ("Ashkenazi", + ["Walker", "Sugar"] ), + new ("Price", + ["Scratches", "Diesel"] ), + new ("Hines", + ["Dusty"] ) ]; // Project the pet owner's name and the pet's name. - var query = - petOwners + var query = petOwners .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName }) .Where(ownerAndPet => ownerAndPet.petName.StartsWith('S')) @@ -2242,16 +2249,16 @@ public static void SelectManyEx3() static class SequenceEqual1 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void SequenceEqualEx1() { - Pet pet1 = new() { Name = "Turbo", Age = 2 }; - Pet pet2 = new() { Name = "Peanut", Age = 8 }; + Pet pet1 = new("Turbo", 2 ); + Pet pet2 = new("Peanut", 8 ); // Create two lists of pets. List pets1 = [pet1, pet2]; @@ -2274,23 +2281,23 @@ The lists are equal. static class SequenceEqual2 { - // - class Pet - { - public string Name { get; set; } - public int Age { get; set; } - } + // + class Pet(string name, int age) + { + public string Name { get; set; } = name; + public int Age { get; set; } = age; + } - public static void SequenceEqualEx2() + public static void SequenceEqualEx2() { - Pet pet1 = new() { Name = "Turbo", Age = 2 }; - Pet pet2 = new() { Name = "Peanut", Age = 8 }; + Pet pet1 = new("Turbo", 2 ); + Pet pet2 = new("Peanut", 8 ); // Create two lists of pets. List pets1 = [pet1, pet2]; List pets2 = - [ new Pet { Name = "Turbo", Age = 2 }, - new Pet { Name = "Peanut", Age = 8 } ]; + [ new ( "Turbo", 2 ), + new ( "Peanut", 8 ) ]; bool equal = pets1.SequenceEqual(pets2); @@ -2325,7 +2332,7 @@ static void SingleEx1() // string[] fruits2 = ["orange", "apple"]; - string fruit2 = null; + string? fruit2 = null; try { @@ -2336,7 +2343,7 @@ static void SingleEx1() Console.WriteLine("The collection does not contain exactly one element."); } - Console.WriteLine(fruit2); + Console.WriteLine(fruit2 ?? "none"); /* This code produces the following output: @@ -2367,20 +2374,17 @@ static void SingleEx2() // // - string fruit2 = null; - try { - fruit2 = fruits.Single(fruit => fruit.Length > 15); + var fruit2 = fruits.Single(fruit => fruit.Length > 15); + Console.WriteLine("sole long Name = {0}", fruit2); } catch (System.InvalidOperationException) { - Console.WriteLine(@"The collection does not contain exactly - one element whose length is greater than 15."); + Console.WriteLine("The collection does not contain exactly\n"+ + "one element whose length is greater than 15."); } - Console.WriteLine(fruit2); - // This code produces the following output: // // The collection does not contain exactly @@ -2395,7 +2399,7 @@ static void SingleOrDefaultEx1() // string[] fruits1 = ["orange"]; - string fruit1 = fruits1.SingleOrDefault(); + var fruit1 = fruits1.SingleOrDefault(); Console.WriteLine(fruit1); @@ -2409,10 +2413,9 @@ static void SingleOrDefaultEx1() // string[] fruits2 = []; - string fruit2 = fruits2.SingleOrDefault(); + var fruit2 = fruits2.SingleOrDefault(); - Console.WriteLine( - string.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2); + Console.WriteLine(fruit2 ?? "No such string!"); /* This code produces the following output: @@ -2428,9 +2431,9 @@ static void SingleOrDefaultEx2() string[] fruits = [ "apple", "banana", "mango", "orange", "passionfruit", "grape" ]; - string fruit1 = fruits.SingleOrDefault(fruit => fruit.Length > 10); + var fruit1 = fruits.SingleOrDefault(fruit => fruit.Length > 10); - Console.WriteLine(fruit1); + Console.WriteLine(fruit1 ?? "none"); /* This code produces the following output: @@ -2440,11 +2443,11 @@ static void SingleOrDefaultEx2() // // - string fruit2 = + var fruit2 = fruits.SingleOrDefault(fruit => fruit.Length > 15); Console.WriteLine( - string.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2); + fruit2 ?? "No such string!"); /* This code produces the following output: @@ -2563,19 +2566,19 @@ static void SkipWhileEx2() static class Sum9 { // - class Package + class Package(string company, double weight) { - public string Company { get; set; } - public double Weight { get; set; } + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; } public static void SumEx1() { List packages = - [ new Package { Company = "Coho Vineyard", Weight = 25.2 }, - new Package { Company = "Lucerne Publishing", Weight = 18.7 }, - new Package { Company = "Wingtip Toys", Weight = 6.0 }, - new Package { Company = "Adventure Works", Weight = 33.8 } ]; + [ new ("Coho Vineyard", 25.2 ), + new ("Lucerne Publishing", 18.7 ), + new ("Wingtip Toys", 6.0 ), + new ("Adventure Works", 33.8 ) ]; double totalWeight = packages.Sum(pkg => pkg.Weight); @@ -2750,8 +2753,7 @@ public static void ThenByDescendingEx1() // Sort the strings first ascending by their length and // then descending using a custom case insensitive comparer. - IEnumerable query = - fruits + IEnumerable query = fruits .OrderBy(fruit => fruit.Length) .ThenByDescending(fruit => fruit, StringComparer.OrdinalIgnoreCase); @@ -2781,19 +2783,19 @@ public static void ThenByDescendingEx1() static class ToArray { // - class Package + class Package(string company, double weight) { - public string Company { get; set; } - public double Weight { get; set; } + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; } public static void ToArrayEx1() { List packages = - [ new Package { Company = "Coho Vineyard", Weight = 25.2 }, - new Package { Company = "Lucerne Publishing", Weight = 18.7 }, - new Package { Company = "Wingtip Toys", Weight = 6.0 }, - new Package { Company = "Adventure Works", Weight = 33.8 } ]; + [ new ("Coho Vineyard", 25.2 ), + new ("Lucerne Publishing", 18.7 ), + new ("Wingtip Toys", 6.0 ), + new ("Adventure Works", 33.8 ) ]; string[] companies = packages.Select(pkg => pkg.Company).ToArray(); @@ -2819,21 +2821,21 @@ Adventure Works // overloads call each other static class ToDictionary { - // - class Package - { - public string Company { get; set; } - public double Weight { get; set; } - public long TrackingNumber { get; set; } - } + // + class Package(string company, double weight, long trackingNumber) + { + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; + public long TrackingNumber { get; set; } = trackingNumber; + } public static void ToDictionaryEx1() { List packages = - [ new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L }, - new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L }, - new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L }, - new Package { Company = "Adventure Works", Weight = 33.8, TrackingNumber = 4665518773L } ]; + [ new ("Coho Vineyard", 25.2, 89453312L ), + new ("Lucerne Publishing", 18.7, 89112755L ), + new ("Wingtip Toys", 6.0, 299456122L ), + new ("Adventure Works", 33.8, 4665518773L ) ]; // Create a Dictionary of Package objects, // using TrackingNumber as the key. @@ -2897,34 +2899,33 @@ static void ToListEx1() static class ToLookup { // - class Package + class Package(string company, double weight, long trackingNumber) { - public string Company { get; set; } - public double Weight { get; set; } - public long TrackingNumber { get; set; } + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; + public long TrackingNumber { get; set; } = trackingNumber; } public static void ToLookupEx1() { // Create a list of Packages. List packages = - [ new Package { Company = "Coho Vineyard", - Weight = 25.2, TrackingNumber = 89453312L }, - new Package { Company = "Lucerne Publishing", - Weight = 18.7, TrackingNumber = 89112755L }, - new Package { Company = "Wingtip Toys", - Weight = 6.0, TrackingNumber = 299456122L }, - new Package { Company = "Contoso Pharmaceuticals", - Weight = 9.3, TrackingNumber = 670053128L }, - new Package { Company = "Wide World Importers", - Weight = 33.8, TrackingNumber = 4665518773L } ]; + [ new ("Coho Vineyard", + 25.2, 89453312L ), + new ("Lucerne Publishing", + 18.7, 89112755L ), + new ("Wingtip Toys", + 6.0, 299456122L ), + new ("Contoso Pharmaceuticals", + 9.3, 670053128L ), + new ("Wide World Importers", + 33.8, 4665518773L ) ]; // Create a Lookup to organize the packages. // Use the first character of Company as the key value. // Select Company appended to TrackingNumber // as the element values of the Lookup. - ILookup lookup = - packages + ILookup lookup = packages .ToLookup(p => p.Company[0], p => p.Company + " " + p.TrackingNumber); @@ -2936,7 +2937,9 @@ public static void ToLookupEx1() // Iterate through each value in the // IGrouping and print its value. foreach (string str in packageGroup) + { Console.WriteLine(" {0}", str); + } } } @@ -3039,7 +3042,9 @@ static void ZipEx() IEnumerable numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second); foreach (string item in numbersAndWords) + { Console.WriteLine(item); + } // This code produces the following output: diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj b/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj index 3248dce4c43..0f763c6eaab 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj @@ -3,6 +3,7 @@ Exe net8.0;net472 + enable Comparers.Program latest diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs b/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs index b95ad6aa6d8..41d0e5116a7 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs @@ -1,31 +1,27 @@ using System; using System.Collections.Generic; using System.Linq; -using System.CodeDom; namespace Comparers; // -public class Product +public class Product(string name, int code) { - public string Name { get; set; } - public int Code { get; set; } + public string Name { get; set; } = name; + public int Code { get; set; } = code; } // Custom comparer for the Product class class ProductComparer : IEqualityComparer { // Products are equal if their names and product numbers are equal. - public bool Equals(Product x, Product y) - { + public bool Equals(Product? x, Product? y) => //Check whether the compared objects reference the same data. - if (ReferenceEquals(x, y)) return true; - - return x is not null && //Check if any of the compared objects is null + ReferenceEquals(x, y) || + ( x is not null && //Check if any of the compared objects is null y is not null && x.Code == y.Code && //Check if the products' properties are equal. - x.Name == y.Name; - } + x.Name == y.Name); // If Equals() returns true for a pair of objects // then GetHashCode() must return the same value for these objects. @@ -49,14 +45,14 @@ public int GetHashCode(Product product) static class Program { - static void Main(string[] args) + static void Main() { // - Product[] store1 = [ new() { Name = "apple", Code = 9 }, - new() { Name = "orange", Code = 4 } ]; + Product[] store1 = [ new("apple",9 ), + new("orange",4 ) ]; - Product[] store2 = [ new() { Name = "apple", Code = 9 }, - new() { Name = "lemon", Code = 12 } ]; + Product[] store2 = [ new("apple",9 ), + new("lemon",12 ) ]; // Get the products from the first array // that have duplicates in the second array. @@ -65,7 +61,9 @@ static void Main(string[] args) store1.Intersect(store2, new ProductComparer()); foreach (Product product in duplicates) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -74,11 +72,11 @@ apple 9 // // - Product[] store10 = [ new() { Name = "apple", Code = 9 }, - new() { Name = "orange", Code = 4 } ]; + Product[] store10 = [ new("apple",9 ), + new("orange",4 ) ]; - Product[] store20 = [ new() { Name = "apple", Code = 9 }, - new() { Name = "lemon", Code = 12 } ]; + Product[] store20 = [ new("apple",9 ), + new("lemon",12 ) ]; //Get the products from the both arrays //excluding duplicates. @@ -87,7 +85,9 @@ apple 9 store10.Union(store20, new ProductComparer()); foreach (Product product in union) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -99,10 +99,10 @@ lemon 12 // // - Product[] products = [ new() { Name = "apple", Code = 9 }, - new() { Name = "orange", Code = 4 }, - new() { Name = "apple", Code = 9 }, - new() { Name = "lemon", Code = 12 } ]; + Product[] products = [ new("apple",9 ), + new("orange",4 ), + new("apple",9 ), + new("lemon",12 ) ]; // Exclude duplicates. @@ -110,7 +110,9 @@ lemon 12 products.Distinct(new ProductComparer()); foreach (Product product in noduplicates) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -121,12 +123,12 @@ lemon 12 // // - Product[] fruits = [ new() { Name = "apple", Code = 9 }, - new() { Name = "orange", Code = 4 }, - new() { Name = "lemon", Code = 12 } ]; + Product[] fruits = [ new("apple",9 ), + new("orange",4 ), + new("lemon",12 ) ]; - Product apple = new() { Name = "apple", Code = 9 }; - Product kiwi = new() { Name = "kiwi", Code = 8 }; + Product apple = new("apple", 9); + Product kiwi = new("kiwi", 8); ProductComparer prodc = new(); @@ -146,11 +148,11 @@ lemon 12 // // - Product[] fruits1 = [ new() { Name = "apple", Code = 9 }, - new() { Name = "orange", Code = 4 }, - new() { Name = "lemon", Code = 12 } ]; + Product[] fruits1 = [ new("apple",9 ), + new("orange",4 ), + new("lemon",12 ) ]; - Product[] fruits2 = [new() { Name = "apple", Code = 9 }]; + Product[] fruits2 = [new("apple", 9)]; // Get all the elements from the first array // except for the elements from the second array. @@ -159,7 +161,9 @@ lemon 12 fruits1.Except(fruits2, new ProductComparer()); foreach (Product product in except) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -172,11 +176,11 @@ lemon 12 // - Product[] storeA = [ new() { Name = "apple", Code = 9 }, - new() { Name = "orange", Code = 4 } ]; + Product[] storeA = [ new("apple",9 ), + new("orange",4 ) ]; - Product[] storeB = [ new() { Name = "apple", Code = 9 }, - new() { Name = "orange", Code = 4 } ]; + Product[] storeB = [ new("apple",9 ), + new("orange",4 ) ]; var equalAB = storeA.SequenceEqual(storeB, new ProductComparer()); @@ -190,6 +194,6 @@ lemon 12 // - Console.ReadLine(); + _ = Console.ReadLine(); } } diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs b/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs index 53b46e24836..e5a323e615d 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs @@ -5,12 +5,12 @@ namespace Comparers; // -public class MyProduct : IEquatable +public class MyProduct(string name, int code) : IEquatable { - public string Name { get; set; } - public int Code { get; set; } + public string Name { get; set; } = name; + public int Code { get; set; } = code; - public bool Equals(MyProduct other) + public bool Equals(MyProduct? other) { //Check whether the compared object is null. if (other is null) return false; @@ -37,23 +37,23 @@ public override int GetHashCode() return hashProductName ^ hashProductCode; } - public override bool Equals(object obj) => Equals(obj as MyProduct); + public override bool Equals(object? obj) => Equals(obj as MyProduct); } // static class Program1 { - static void Main(string[] args) + static void Main() { // This snippet is different than #2 by using ProductA (not Product). // Some samples here need to use ProductA in conjunction with // ProductComparer, which implements IEqualityComparer (not IEquatable). // - ProductA[] store1 = [ new() { Name = "apple", Code = 9 }, - new() { Name = "orange", Code = 4 } ]; + ProductA[] store1 = [ new("apple", 9 ), + new("orange", 4 ) ]; - ProductA[] store2 = [ new() { Name = "apple", Code = 9 }, - new() { Name = "lemon", Code = 12 } ]; + ProductA[] store2 = [ new("apple", 9 ), + new("lemon", 12 ) ]; // // @@ -64,7 +64,9 @@ static void Main(string[] args) store1.Intersect(store2); foreach (ProductA product in duplicates) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -77,10 +79,12 @@ apple 9 //excluding duplicates. IEnumerable union = - store1.Union(store2); + store1.Union(store2); foreach (ProductA product in union) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -92,10 +96,10 @@ lemon 12 // // - MyProduct[] products = [ new() { Name = "apple", Code = 9 }, - new() { Name = "orange", Code = 4 }, - new() { Name = "apple", Code = 9 }, - new() { Name = "lemon", Code = 12 } ]; + MyProduct[] products = [ new("apple", 9 ), + new("orange", 4 ), + new("apple", 9 ), + new("lemon", 12 ) ]; // Exclude duplicates. @@ -103,7 +107,9 @@ lemon 12 products.Distinct(); foreach (MyProduct product in noduplicates) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -114,11 +120,11 @@ lemon 12 // // - ProductA[] fruits1 = [ new() { Name = "apple", Code = 9 }, - new() { Name = "orange", Code = 4 }, - new() { Name = "lemon", Code = 12 } ]; + ProductA[] fruits1 = [ new("apple", 9 ), + new("orange", 4 ), + new("lemon", 12 ) ]; - ProductA[] fruits2 = [new() { Name = "apple", Code = 9 }]; + ProductA[] fruits2 = [new("apple", 9 )]; // Get all the elements from the first array // except for the elements from the second array. @@ -127,7 +133,9 @@ lemon 12 fruits1.Except(fruits2); foreach (ProductA product in except) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -139,11 +147,11 @@ lemon 12 // - ProductA[] storeA = [ new() { Name = "apple", Code = 9 }, - new() { Name = "orange", Code = 4 } ]; + ProductA[] storeA = [ new("apple", 9 ), + new("orange", 4 ) ]; - ProductA[] storeB = [ new() { Name = "apple", Code = 9 }, - new() { Name = "orange", Code = 4 } ]; + ProductA[] storeB = [ new("apple", 9 ), + new("orange", 4 ) ]; var equalAB = storeA.SequenceEqual(storeB); @@ -159,20 +167,17 @@ lemon 12 } // - public class ProductA : IEquatable + public class ProductA(string name, int code) : IEquatable { - public string Name { get; set; } - public int Code { get; set; } + public string Name { get; set; } = name; + public int Code { get; set; } = code; - public bool Equals(ProductA other) - { - if (other is null) - return false; - - return Name == other.Name && Code == other.Code; - } + public bool Equals(ProductA? other) => + other is not null && + Name == other.Name && + Code == other.Code; - public override bool Equals(object obj) => Equals(obj as ProductA); + public override bool Equals(object? obj) => Equals(obj as ProductA); public override int GetHashCode() => (Name, Code).GetHashCode(); } // diff --git a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj index 0eddc23065a..e1cea776ebd 100644 --- a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj +++ b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj @@ -1,8 +1,9 @@ - + Library net8.0 + enable @@ -11,5 +12,5 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - + \ No newline at end of file diff --git a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/igrouping.cs b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/igrouping.cs index ec51757f6ae..f7857290b08 100644 --- a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/igrouping.cs +++ b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/igrouping.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Linq; //using System.Reflection; @@ -8,26 +7,30 @@ namespace SequenceExamples { static class IGrouping { - static void Main() => + static void Main() + { //Console.WriteLine("\n"); //GroupKey(); EnumerateGroup(); + } - private static void EnumerateGroup() + static void EnumerateGroup() { // // Get an IGrouping object. IGrouping group = - typeof(string).GetMembers(). - GroupBy(member => member.MemberType). - First(); + typeof(string).GetMembers() + .GroupBy(member => member.MemberType) + .First(); // Output the key of the IGrouping, then iterate // through each value in the sequence of values // of the IGrouping and output its Name property. Console.WriteLine("\nValues that have the key '{0}':", group.Key); foreach (System.Reflection.MemberInfo mi in group) + { Console.WriteLine(mi.Name); + } // The output is similar to: @@ -52,7 +55,7 @@ private static void EnumerateGroup() // } - private static void GroupKey() + static void GroupKey() { // // Get a sequence of IGrouping objects. @@ -62,7 +65,9 @@ private static void GroupKey() // Output the key of each IGrouping object and the count of values. foreach (IGrouping group in memberQuery) + { Console.WriteLine("(Key) {0} (Member count) {1}", group.Key, group.Count()); + } // The output is similar to: // (Key) Method (Member count) 113 @@ -73,7 +78,7 @@ private static void GroupKey() // } - private static void Test() + static void Test() { IOrderedEnumerable> memberQuery = typeof(string).GetMembers(). @@ -84,7 +89,9 @@ private static void Test() { Console.WriteLine("\n(Key) {0}", group.Key); foreach (System.Reflection.MemberInfo mi in group) + { Console.WriteLine(mi.Name); + } } } } diff --git a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs index 38cc3039746..2ae985202df 100644 --- a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs +++ b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Linq; @@ -10,22 +9,22 @@ static class ILookup static void Main() => ILookupExample(); // - class Package + class Package(string company, double weight, long trackingNumber) { - public string Company { get; set; } - public double Weight { get; set; } - public long TrackingNumber { get; set; } + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; + public long TrackingNumber { get; set; } = trackingNumber; } public static void ILookupExample() { // Create a list of Packages to put into an ILookup data structure. List packages = - [ new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L }, - new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L }, - new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L }, - new Package { Company = "Contoso Pharmaceuticals", Weight = 9.3, TrackingNumber = 670053128L }, - new Package { Company = "Wide World Importers", Weight = 33.8, TrackingNumber = 4665518773L } ]; + [ new Package ("Coho Vineyard", 25.2, 89453312L ), + new Package ("Lucerne Publishing", 18.7, 89112755L ), + new Package ("Wingtip Toys", 6.0, 299456122L ), + new Package ("Contoso Pharmaceuticals", 9.3, 670053128L ), + new Package ("Wide World Importers", 33.8, 4665518773L ) ]; // Create a Lookup to organize the packages. Use the first character of Company as the key value. // Select Company appended to TrackingNumber for each element value in the ILookup object. @@ -41,7 +40,9 @@ public static void ILookupExample() Console.WriteLine(packageGroup.Key); // Iterate through each value in the collection. foreach (string str in packageGroup) + { Console.WriteLine(" {0}", str); + } } // This code produces the following output: diff --git a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj index 0eddc23065a..e1cea776ebd 100644 --- a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj +++ b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj @@ -1,8 +1,9 @@ - + Library net8.0 + enable @@ -11,5 +12,5 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - + \ No newline at end of file diff --git a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.cs b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.cs index d0b45b843ac..139217b6f53 100644 --- a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.cs +++ b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Linq; @@ -23,7 +22,9 @@ static void Example1() // Output the resulting sequence of strings. foreach (string fruit in sortedFruits1) + { Console.WriteLine(fruit); + } // This code produces the following output: // @@ -56,7 +57,9 @@ static void Example2() // Output the resulting sequence of strings. foreach (string fruit in sortedFruits3) + { Console.WriteLine(fruit); + } // This code produces the following output: // diff --git a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj index 0eddc23065a..e1cea776ebd 100644 --- a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj +++ b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj @@ -1,8 +1,9 @@ - + Library net8.0 + enable @@ -11,5 +12,5 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - + \ No newline at end of file diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj b/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj index 48a0fef22a0..a1e576757e6 100644 --- a/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj +++ b/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj @@ -1,8 +1,9 @@ - + Library net8.0 + enable diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs b/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs index d23b3866a81..6260045d6af 100644 --- a/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs +++ b/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs @@ -25,7 +25,7 @@ static void AggregateEx1() // Use Aggregate() to prepend each word to the beginning of the // new sentence to reverse the word order. string reversed = - words.AsQueryable().Aggregate( + words.Aggregate( (workingSentence, next) => next + " " + workingSentence ); @@ -44,7 +44,7 @@ static void AggregateEx2() // Count the even numbers in the array, using a seed value of 0. int numEven = - ints.AsQueryable().Aggregate( + ints.Aggregate( 0, (total, next) => next % 2 == 0 ? total + 1 : total ); @@ -64,7 +64,7 @@ static void AggregateEx3() // Determine whether any string in the array is longer than "banana". string longestName = - fruits.AsQueryable() + fruits .Aggregate( "banana", (longest, next) => next.Length > longest.Length ? next : longest, @@ -89,7 +89,7 @@ public static class All // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } @@ -102,7 +102,7 @@ public static void AllEx1() // Determine whether all pet names in the array start with 'B'. bool allStartWithB = - pets.AsQueryable().All(pet => pet.Name.StartsWith('B')); + pets.All(pet => pet.Name.StartsWith('B')); Console.WriteLine( "{0} pet names start with 'B'.", @@ -121,13 +121,13 @@ static class All2 // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } class Person { - public string LastName { get; set; } - public Pet[] Pets { get; set; } + public required string LastName { get; set; } + public required Pet[] Pets { get; set; } } public static void AllEx2() @@ -148,11 +148,13 @@ public static void AllEx2() // Determine which people have pets that are all older than 5. IEnumerable names = from person in people - where person.Pets.AsQueryable().All(pet => pet.Age > 5) + where person.Pets.All(pet => pet.Age > 5) select person.LastName; foreach (string name in names) + { Console.WriteLine(name); + } /* This code produces the following output: * @@ -173,7 +175,7 @@ public static void AnyEx1() List numbers = [1, 2]; // Determine if the list contains any elements. - bool hasElements = numbers.AsQueryable().Any(); + bool hasElements = numbers.Any(); // [CA1860] better to use "numbers.Count != 0;" ! Console.WriteLine("The list {0} empty.", hasElements ? "is not" : "is"); @@ -188,13 +190,13 @@ public static void AnyEx1() // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } class Person { - public string LastName { get; set; } - public Pet[] Pets { get; set; } + public required string LastName { get; set; } + public required Pet[] Pets { get; set; } } public static void AnyEx2() @@ -215,11 +217,13 @@ public static void AnyEx2() // Determine which people have a non-empty Pet array. IEnumerable names = from person in people - where person.Pets.AsQueryable().Any() + where person.Pets.Any() // [CA1860] better to use "where person.Pets.Length != 0" select person.LastName; foreach (string name in names) + { Console.WriteLine(name); + } /* This code produces the following output: @@ -236,7 +240,7 @@ static class Any2 // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } public bool Vaccinated { get; set; } } @@ -251,7 +255,7 @@ public static void AnyEx3() // Determine whether any pets over age 1 are also unvaccinated. bool unvaccinated = - pets.AsQueryable().Any(p => p.Age > 1 && !p.Vaccinated); + pets.Any(p => p.Age > 1 && !p.Vaccinated); Console.WriteLine( "There {0} unvaccinated animals over age one.", @@ -301,7 +305,7 @@ static void AverageEx1() // List grades = [78, 92, 100, 37, 81]; - double average = grades.AsQueryable().Average(); + double average = grades.Average(); Console.WriteLine("The average grade is {0}.", average); @@ -317,7 +321,7 @@ static void AverageEx2() // long?[] longs = [null, 10007L, 37L, 399846234235L]; - double? average = longs.AsQueryable().Average(); + double? average = longs.Average(); Console.WriteLine("The average is {0}.", average); @@ -334,7 +338,7 @@ static void AverageEx3() string[] fruits = ["apple", "banana", "mango", "orange", "passionfruit", "grape"]; // Determine the average string length in the array. - double average = fruits.AsQueryable().Average(s => s.Length); + double average = fruits.Average(s => s.Length); Console.WriteLine("The average string length is {0}.", average); @@ -356,14 +360,15 @@ static void CastEx1() // Cast each MethodInfo object to a MemberInfo object. // Then select the names of those methods whose names // are less than 6 characters long. - IQueryable members = - methods.AsQueryable() + IQueryable members = methods.AsQueryable() .Cast() .Select(member => member.Name) .Where(name => name.Length < 6); foreach (string member in members) + { Console.WriteLine(member); + } /* This code produces the following output: @@ -387,18 +392,18 @@ static void CastEx2() // // Create a list of objects. - List words = - ["green", "blue", "violet"]; + List words = ["green", "blue", "violet"]; // Cast the objects in the list to type 'string' // and project the first letter of each string. - IEnumerable query = - words.AsQueryable() + IEnumerable query = words .Cast() .Select(str => str.Substring(0, 1)); foreach (string s in query) + { Console.WriteLine(s); + } /* This code produces the following output: @@ -417,7 +422,7 @@ static class Concat // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } @@ -446,13 +451,14 @@ public static void ConcatEx1() // Concatenate a collection of cat names to a // collection of dog names by using Concat(). - IEnumerable query = - cats.AsQueryable() + IEnumerable query = cats .Select(cat => cat.Name) .Concat(dogs.Select(dog => dog.Name)); foreach (string name in query) + { Console.WriteLine(name); + } } // This code produces the following output: @@ -477,10 +483,12 @@ public static void ConcatEx2() IEnumerable query = new[] { cats.Select(cat => cat.Name), dogs.Select(dog => dog.Name) } - .AsQueryable().SelectMany(name => name); + .SelectMany(name => name); foreach (string name in query) + { Console.WriteLine(name); + } // This code produces the following output: // @@ -506,7 +514,7 @@ static void ContainsEx1() // The string to search for in the array. const string mango = "mango"; - bool hasMango = fruits.AsQueryable().Contains(mango); + bool hasMango = fruits.Contains(mango); Console.WriteLine( "The array {0} contain '{1}'.", @@ -528,7 +536,7 @@ static void CountEx1() string[] fruits = [ "apple", "banana", "mango", "orange", "passionfruit", "grape" ]; - int numberOfFruits = fruits.AsQueryable().Count(); + int numberOfFruits = fruits.Count(); // [CA1829, RCS1077] better to use "fruits.Length;" Console.WriteLine( "There are {0} items in the array.", @@ -546,7 +554,7 @@ static class Count // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public bool Vaccinated { get; set; } } @@ -559,7 +567,7 @@ public static void CountEx2() // Count the number of unvaccinated pets in the array. int numberUnvaccinated = - pets.AsQueryable().Count(p => !p.Vaccinated); + pets.Count(p => !p.Vaccinated); Console.WriteLine( "There are {0} unvaccinated animals.", @@ -580,7 +588,7 @@ static class DefaultIfEmpty1 // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } @@ -596,7 +604,7 @@ public static void DefaultIfEmptyEx1() // returns, so that if the initial list is empty, there // will always be at least one item in the returned array. string[] names = - [.. pets.AsQueryable() + [.. pets .Select(pet => pet.Name) .DefaultIfEmpty()]; @@ -625,17 +633,17 @@ public static void DefaultIfEmptyEx1a() // DefaultIfEmpty(). This code passes an (optional) default // value to DefaultIfEmpty(). string[] oldPets = - [.. pets.AsQueryable() - .Where(pet => pet.Age >= 10) - .Select(pet => pet.Name) - .DefaultIfEmpty("[EMPTY]")]; + [.. pets + .Where(pet => pet.Age >= 10) + .Select(pet => pet.Name) + .DefaultIfEmpty("[EMPTY]")]; Console.WriteLine("First query: " + oldPets[0]); // This query selects only those pets that are 10 or older. // This code does not call DefaultIfEmpty(). string[] oldPets2 = - [.. pets.AsQueryable() + [.. pets .Where(pet => pet.Age >= 10) .Select(pet => pet.Name)]; @@ -645,7 +653,7 @@ [.. pets.AsQueryable() { Console.WriteLine("Second query: " + oldPets2[0]); } - catch (Exception e) + catch (ApplicationException e) { Console.WriteLine("Second query: An exception was thrown: " + e.Message); } @@ -668,12 +676,14 @@ static void DistinctEx1() // List ages = [21, 46, 46, 55, 17, 21, 55, 55]; - IEnumerable distinctAges = ages.AsQueryable().Distinct(); + IEnumerable distinctAges = ages.Distinct(); Console.WriteLine("Distinct ages:"); foreach (int age in distinctAges) + { Console.WriteLine(age); + } /* This code produces the following output: @@ -700,7 +710,8 @@ static void ElementAtEx1() Random random = new(DateTime.Now.Millisecond); string name = - names.AsQueryable().ElementAt(random.Next(0, names.Length)); + names.ElementAt(random.Next(0, names.Length)); + //names[random.Next(0, names.Length)]; // simpler Console.WriteLine("The name chosen at random is '{0}'.", name); @@ -725,12 +736,12 @@ static void ElementAtOrDefaultEx1() const int index = 20; - string name = names.AsQueryable().ElementAtOrDefault(index); + var name = names.ElementAtOrDefault(index); Console.WriteLine( "The name chosen at index {0} is '{1}'.", index, - string.IsNullOrEmpty(name) ? "[NONE AT THIS INDEX]" : name); + (name) ?? "[NONE AT THIS INDEX]"); /* This code produces the following output: @@ -752,10 +763,12 @@ static void ExceptEx1() // Get the numbers from the first array that // are NOT in the second array. IEnumerable onlyInFirstSet = - numbers1.AsQueryable().Except(numbers2); + numbers1.Except(numbers2); foreach (double number in onlyInFirstSet) + { Console.WriteLine(number); + } /* This code produces the following output: @@ -778,7 +791,8 @@ static void FirstEx1() int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19 ]; - int first = numbers.AsQueryable().First(); + int first = numbers.First(); + //int first = numbers[0]; // simpler Console.WriteLine(first); @@ -798,7 +812,7 @@ static void FirstEx2() 83, 23, 87, 435, 67, 12, 19 ]; // Get the first number in the array that is greater than 80. - int first = numbers.AsQueryable().First(number => number > 80); + int first = numbers.First(number => number > 80); Console.WriteLine(first); @@ -820,7 +834,7 @@ static void FirstOrDefaultEx1() int[] numbers = []; // Get the first item in the array, or else the // default value for type int (0). - int first = numbers.AsQueryable().FirstOrDefault(); + int first = numbers.FirstOrDefault(); Console.WriteLine(first); @@ -843,20 +857,20 @@ static void FirstOrDefaultEx2() // Get the first string in the array that is longer // than 20 characters, or the default value for type // string (null) if none exists. - string firstLongName = - names.AsQueryable().FirstOrDefault(name => name.Length > 20); + var firstLongName = + names.FirstOrDefault(name => name.Length > 20); Console.WriteLine("The first long name is '{0}'.", firstLongName); // Get the first string in the array that is longer // than 30 characters, or the default value for type // string (null) if none exists. - string firstVeryLongName = - names.AsQueryable().FirstOrDefault(name => name.Length > 30); + var firstVeryLongName = + names.FirstOrDefault(name => name.Length > 30); Console.WriteLine( "There is {0} name that is longer than 30 characters.", - string.IsNullOrEmpty(firstVeryLongName) ? "NOT a" : "a"); + firstVeryLongName is null ? "NOT a" : "a"); /* This code produces the following output: @@ -874,7 +888,7 @@ static void FirstOrDefaultEx3() List months = []; // Setting the default value to 1 after the query. - int firstMonth1 = months.AsQueryable().FirstOrDefault(); + int firstMonth1 = months.FirstOrDefault(); if (firstMonth1 == 0) { firstMonth1 = 1; @@ -882,7 +896,7 @@ static void FirstOrDefaultEx3() Console.WriteLine("The value of the firstMonth1 variable is {0}", firstMonth1); // Setting the default value to 1 by using DefaultIfEmpty() in the query. - int firstMonth2 = months.AsQueryable().DefaultIfEmpty(1).First(); + int firstMonth2 = months.DefaultIfEmpty(1).First(); Console.WriteLine("The value of the firstMonth2 variable is {0}", firstMonth2); /* @@ -902,7 +916,7 @@ static class GroupBy // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } @@ -917,7 +931,7 @@ public static void GroupByEx1() // Group the pets using Pet.Age as the key. // Use Pet.Name as the value for each entry. - IQueryable> query = pets.AsQueryable() + var query = pets .GroupBy(pet => pet.Age); // Iterate over each IGrouping in the collection. @@ -944,7 +958,7 @@ static class GroupBy2 // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } @@ -960,7 +974,7 @@ public static void GroupByEx2() // Group the pets using Pet.Age as the key. // Use Pet.Name as the value for each entry. IEnumerable> query = - pets.AsQueryable().GroupBy(pet => pet.Age, pet => pet.Name); + pets.GroupBy(pet => pet.Age, pet => pet.Name); // Iterate over each IGrouping in the collection. foreach (IGrouping petGroup in query) @@ -970,7 +984,9 @@ public static void GroupByEx2() // Iterate over each value in the // IGrouping and print the value. foreach (string name in petGroup) + { Console.WriteLine(" {0}", name); + } } } @@ -995,7 +1011,7 @@ static class GroupBy3 // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public double Age { get; set; } } @@ -1012,7 +1028,7 @@ public static void GroupByEx3() // Then project an anonymous type from each group // that consists of the key, the count of the group's // elements, and the minimum and maximum age in the group. - var query = petsList.AsQueryable().GroupBy( + var query = petsList.GroupBy( pet => Math.Floor(pet.Age), (age, pets) => new { @@ -1058,7 +1074,7 @@ static class GroupBy4 // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public double Age { get; set; } } @@ -1075,7 +1091,7 @@ public static void GroupByEx4() // Then project an anonymous type from each group // that consists of the key, the count of the group's // elements, and the minimum and maximum age in the group. - var query = petsList.AsQueryable().GroupBy( + var query = petsList.GroupBy( pet => Math.Floor(pet.Age), pet => pet.Age, (baseAge, ages) => new @@ -1123,13 +1139,13 @@ static class GroupJoin // class Person { - public string Name { get; set; } + public required string Name { get; set; } } class Pet { - public string Name { get; set; } - public Person Owner { get; set; } + public required string Name { get; set; } + public required Person Owner { get; set; } } public static void GroupJoinEx1() @@ -1150,7 +1166,7 @@ public static void GroupJoinEx1() // type that contains a person's name and a collection // of names of the pets that are owned by them. var query = - people.AsQueryable().GroupJoin(pets, + people.GroupJoin(pets, person => person, pet => pet.Owner, (person, petCollection) => @@ -1166,7 +1182,9 @@ public static void GroupJoinEx1() Console.WriteLine("{0}:", obj.OwnerName); // Output each of the owner's pet's names. foreach (string pet in obj.Pets) + { Console.WriteLine(" {0}", pet); + } } } @@ -1194,10 +1212,12 @@ static void IntersectEx1() int[] id2 = [39, 59, 83, 47, 26, 4, 30]; // Get the numbers that occur in both arrays (id1 and id2). - IEnumerable both = id1.AsQueryable().Intersect(id2); + IEnumerable both = id1.Intersect(id2); foreach (int id in both) + { Console.WriteLine(id); + } /* This code produces the following output: @@ -1216,13 +1236,13 @@ static class Join // class Person { - public string Name { get; set; } + public required string Name { get; set; } } class Pet { - public string Name { get; set; } - public Person Owner { get; set; } + public required string Name { get; set; } + public required Person Owner { get; set; } } public static void JoinEx1() @@ -1243,7 +1263,7 @@ public static void JoinEx1() // to create a list of person-pet pairs where each element is // an anonymous type that contains the name of pet and the name // of the person that owns the pet. - var query = people.AsQueryable().Join(pets, + var query = people.Join(pets, person => person, pet => pet.Owner, (person, pet) => @@ -1278,7 +1298,8 @@ static void LastEx1() int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 67, 12, 19 ]; - int last = numbers.AsQueryable().Last(); + int last = numbers.Last(); + //int last = numbers[^1]; // simpler Console.WriteLine(last); @@ -1298,7 +1319,7 @@ static void LastEx2() 83, 23, 87, 67, 12, 19 ]; // Get the last number in the array that is greater than 80. - int last = numbers.AsQueryable().Last(num => num > 80); + int last = numbers.Last(num => num > 80); Console.WriteLine(last); @@ -1321,10 +1342,10 @@ static void LastOrDefaultEx1() // Get the last item in the array, or else the default // value for type string (null). - string last = fruits.AsQueryable().LastOrDefault(); + var last = fruits.LastOrDefault(); Console.WriteLine( - string.IsNullOrEmpty(last) ? "[STRING IS NULL OR EMPTY]" : last); + last ?? "[STRING IS NULL OR EMPTY]"); /* This code produces the following output: @@ -1343,7 +1364,7 @@ static void LastOrDefaultEx2() // Get the last number in the array that rounds to 50.0, // or else the default value for type double (0.0). double last50 = - numbers.AsQueryable() + numbers .LastOrDefault(n => Math.Round(n) == 50.0); Console.WriteLine("The last number that rounds to 50 is {0}.", last50); @@ -1351,7 +1372,7 @@ static void LastOrDefaultEx2() // Get the last number in the array that rounds to 40.0, // or else the default value for type double (0.0). double last40 = - numbers.AsQueryable() + numbers .LastOrDefault(n => Math.Round(n) == 40.0); Console.WriteLine( @@ -1374,7 +1395,7 @@ static void LastOrDefaultEx3() List daysOfMonth = []; // Setting the default value to 1 after the query. - int lastDay1 = daysOfMonth.AsQueryable().LastOrDefault(); + int lastDay1 = daysOfMonth.LastOrDefault(); if (lastDay1 == 0) { lastDay1 = 1; @@ -1382,7 +1403,7 @@ static void LastOrDefaultEx3() Console.WriteLine("The value of the lastDay1 variable is {0}", lastDay1); // Setting the default value to 1 by using DefaultIfEmpty() in the query. - int lastDay2 = daysOfMonth.AsQueryable().DefaultIfEmpty(1).Last(); + int lastDay2 = daysOfMonth.DefaultIfEmpty(1).Last(); Console.WriteLine("The value of the lastDay2 variable is {0}", lastDay2); /* @@ -1402,7 +1423,7 @@ public static void LongCountEx1() string[] fruits = [ "apple", "banana", "mango", "orange", "passionfruit", "grape" ]; - long count = fruits.AsQueryable().LongCount(); + long count = fruits.LongCount(); // [CA1829] better to use "fruits.Length;" Console.WriteLine("There are {0} fruits in the collection.", count); @@ -1420,7 +1441,7 @@ static class LongCount // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } @@ -1433,7 +1454,7 @@ public static void LongCountEx2() const int Age = 3; // Count the number of Pet objects where Pet.Age is greater than 3. - long count = pets.AsQueryable() + long count = pets .LongCount(pet => pet.Age > Age); Console.WriteLine("There are {0} animals over age {1}.", count, Age); @@ -1455,7 +1476,7 @@ static void MaxEx1() // List longs = [4294967296L, 466855135L, 81125L]; - long max = longs.AsQueryable().Max(); + var max = longs.Max(); Console.WriteLine("The largest number is {0}.", max); @@ -1473,7 +1494,7 @@ static class Max2 // with a selector // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } @@ -1485,8 +1506,7 @@ public static void MaxEx2() // Add Pet.Age to the length of Pet.Name // to determine the "maximum" Pet object in the array. - int max = - pets.AsQueryable().Max(pet => pet.Age + pet.Name.Length); + var max = pets.Max(pet => pet.Age + pet.Name.Length); Console.WriteLine( "The maximum pet age plus name length is {0}.", @@ -1510,7 +1530,7 @@ static void MinEx1() // double[] doubles = [1.5E+104, 9E+103, -2E+103]; - double min = doubles.AsQueryable().Min(); + var min = doubles.Min(); Console.WriteLine("The smallest number is {0}.", min); @@ -1528,7 +1548,7 @@ static class Min2 // with a selector // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } @@ -1539,7 +1559,7 @@ public static void MinEx2() new() { Name="Whiskers", Age=1 } ]; // Get the Pet object that has the smallest Age value. - int min = pets.AsQueryable().Min(pet => pet.Age); + var min = pets.Min(pet => pet.Age); Console.WriteLine("The youngest animal is age {0}.", min); } @@ -1562,12 +1582,14 @@ static void OfTypeEx1() List members = [.. typeof(string).GetMembers()]; // Return only those items that can be cast to type PropertyInfo. - IQueryable propertiesOnly = - members.AsQueryable().OfType(); + var propertiesOnly = + members.OfType(); Console.WriteLine("Members of type 'PropertyInfo' are:"); foreach (System.Reflection.PropertyInfo pi in propertiesOnly) + { Console.WriteLine(pi.Name); + } /* This code produces the following output: @@ -1587,7 +1609,7 @@ static class OrderBy // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } @@ -1598,11 +1620,12 @@ public static void OrderByEx1() new() { Name="Whiskers", Age=1 } ]; // Sort the Pet objects in the array by Pet.Age. - IEnumerable query = - pets.AsQueryable().OrderBy(pet => pet.Age); + IEnumerable query = pets.OrderBy(pet => pet.Age); foreach (Pet pet in query) + { Console.WriteLine("{0} - {1}", pet.Name, pet.Age); + } } /* @@ -1660,12 +1683,10 @@ public int Compare(decimal d1, decimal d2) fractional2 = d2; } - if (fractional1 == fractional2) - return decimal.Compare(d1, d2); - else if (fractional1 > fractional2) - return 1; - else - return -1; + return fractional1 == fractional2 + ? decimal.Compare(d1, d2) + : fractional1 > fractional2 + ? 1 : -1; } } @@ -1677,11 +1698,13 @@ public static void OrderByDescendingEx1() // Sort the decimal values in descending order // by using a custom comparer. IEnumerable query = - decimals.AsQueryable() + decimals .OrderByDescending(num => num, new SpecialComparer()); foreach (decimal num in query) + { Console.WriteLine(num); + } } /* @@ -1706,10 +1729,13 @@ static void ReverseEx1() char[] apple = ['a', 'p', 'p', 'l', 'e']; // Reverse the order of the characters in the collection. - IQueryable reversed = apple.AsQueryable().Reverse(); + var reversed = apple.Reverse(); foreach (char chr in reversed) + { Console.Write(chr + " "); + } + Console.WriteLine(); /* @@ -1731,10 +1757,12 @@ static void SelectEx1() // Project the square of each int value. IEnumerable squares = - range.AsQueryable().Select(x => x * x); + range.Select(x => x * x); foreach (int num in squares) + { Console.WriteLine(num); + } /* This code produces the following output: @@ -1764,13 +1792,14 @@ static void SelectEx2() // index of the string in the source array, and // a string that contains the same number of characters // as the string's index in the source array. - var query = - fruits.AsQueryable() + var query = fruits .Select((fruit, index) => - new { index, str = fruit.Substring(0, index) }); + new { index, str = fruit[..index] }); foreach (var obj in query) + { Console.WriteLine("{0}", obj); + } /* This code produces the following output: @@ -1793,8 +1822,8 @@ static class SelectMany1 // class PetOwner { - public string Name { get; set; } - public List Pets { get; set; } + public required string Name { get; set; } + public required List Pets { get; set; } } public static void SelectManyEx1() @@ -1809,7 +1838,7 @@ public static void SelectManyEx1() // Query using SelectMany(). IEnumerable query1 = - petOwners.AsQueryable() + petOwners .SelectMany(petOwner => petOwner.Pets); Console.WriteLine("Using SelectMany():"); @@ -1817,11 +1846,13 @@ public static void SelectManyEx1() // Only one foreach loop is required to iterate through the // results because it is a one-dimensional collection. foreach (string pet in query1) + { Console.WriteLine(pet); + } // This code shows how to use Select() instead of SelectMany(). IEnumerable> query2 = - petOwners.AsQueryable() + petOwners .Select(petOwner => petOwner.Pets); Console.WriteLine("\nUsing Select():"); @@ -1868,8 +1899,8 @@ static class SelectMany2 // class PetOwner { - public string Name { get; set; } - public List Pets { get; set; } + public required string Name { get; set; } + public required List Pets { get; set; } } public static void SelectManyEx2() @@ -1888,14 +1919,15 @@ public static void SelectManyEx2() // project a sequence of strings where each string // consists of the index of the PetOwner element in the // source array and the name of each pet in PetOwner.Pets. - IEnumerable query = - petOwners.AsQueryable() + IEnumerable query = petOwners .SelectMany( - (petOwner, index) => petOwner.Pets.Select(pet => index + pet) + (petOwner, index) => petOwner.Pets.Select(pet => index + pet) ); foreach (string pet in query) + { Console.WriteLine(pet); + } } // This code produces the following output: @@ -1916,14 +1948,14 @@ static class SelectMany3 // class PetOwner { - public string Name { get; set; } - public List Pets { get; set; } + public required string Name { get; set; } + public required List Pets { get; set; } } class Pet { - public string Name { get; set; } - public string Breed { get; set; } + public required string Name { get; set; } + public required string Breed { get; set; } } public static void SelectManyEx3() @@ -1949,8 +1981,7 @@ public static void SelectManyEx3() // This query demonstrates how to obtain a sequence of // the names of all the pets whose breed is "Collie", while // keeping an association with the owner that owns the pet. - var query = - petOwners.AsQueryable() + var query = petOwners // Create a sequence of ALL the Pet objects. Then // project an anonymous type that consists of each // Pet in the new sequence and the PetOwner object @@ -1970,7 +2001,9 @@ public static void SelectManyEx3() // Print the results. foreach (var obj in query) + { Console.WriteLine(obj); + } } /* This code produces the following output: @@ -1990,7 +2023,7 @@ static class SequenceEqual1 // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } @@ -2004,7 +2037,7 @@ public static void SequenceEqualEx1() List pets2 = [pet1, pet2]; // Determine if the lists are equal. - bool equal = pets1.AsQueryable().SequenceEqual(pets2); + bool equal = pets1.SequenceEqual(pets2); Console.WriteLine( "The lists {0} equal.", @@ -2025,7 +2058,7 @@ static class SequenceEqual2 // class Pet { - public string Name { get; set; } + public required string Name { get; set; } public int Age { get; set; } } @@ -2043,7 +2076,7 @@ public static void SequenceEqualEx2() ]; // Determine if the lists are equal. - bool equal = pets1.AsQueryable().SequenceEqual(pets2); + bool equal = pets1.SequenceEqual(pets2); Console.WriteLine("The lists {0} equal.", equal ? "are" : "are NOT"); } @@ -2067,14 +2100,14 @@ static void SingleEx1() string[] fruits2 = ["orange", "apple"]; // Get the only item in the first array. - string fruit1 = fruits1.AsQueryable().Single(); + string fruit1 = fruits1.Single(); Console.WriteLine("First query: " + fruit1); try { // Try to get the only item in the second array. - string fruit2 = fruits2.AsQueryable().Single(); + string fruit2 = fruits2.Single(); Console.WriteLine("Second query: " + fruit2); } catch (System.InvalidOperationException) @@ -2104,7 +2137,7 @@ static void SingleEx2() "orange", "passionfruit", "grape" ]; // Get the only string in the array whose length is greater than 10. - string fruit1 = fruits.AsQueryable() + string fruit1 = fruits .Single(fruit => fruit.Length > 10); Console.WriteLine("First Query: " + fruit1); @@ -2113,7 +2146,7 @@ static void SingleEx2() { // Try to get the only string in the array // whose length is greater than 15. - string fruit2 = fruits.AsQueryable() + string fruit2 = fruits .Single(fruit => fruit.Length > 15); Console.WriteLine("Second Query: " + fruit2); } @@ -2145,14 +2178,13 @@ static void SingleOrDefaultEx1() // Get the only item in the first array, or else // the default value for type string (null). - string fruit1 = fruits1.AsQueryable().SingleOrDefault(); + var fruit1 = fruits1.SingleOrDefault(); Console.WriteLine("First Query: " + fruit1); // Get the only item in the second array, or else // the default value for type string (null). - string fruit2 = fruits2.AsQueryable().SingleOrDefault(); - Console.WriteLine("Second Query: " + - (string.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2)); + var fruit2 = fruits2.SingleOrDefault(); + Console.WriteLine("Second Query: " + fruit2 ?? "No such string!"); /* This code produces the following output: @@ -2172,16 +2204,16 @@ static void SingleOrDefaultEx2() // Get the single string in the array whose length is greater // than 10, or else the default value for type string (null). - string fruit1 = fruits.AsQueryable() + var fruit1 = fruits .SingleOrDefault(fruit => fruit.Length > 10); Console.WriteLine("First Query: " + fruit1); // Get the single string in the array whose length is greater // than 15, or else the default value for type string (null). - string fruit2 = fruits.AsQueryable() + var fruit2 = fruits .SingleOrDefault(fruit => fruit.Length > 15); Console.WriteLine("Second Query: " + - (string.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2)); + fruit2 ?? "No such string!"); /* This code produces the following output: @@ -2199,7 +2231,7 @@ static void SingleOrDefaultEx3() int[] pageNumbers = []; // Setting the default value to 1 after the query. - int pageNumber1 = pageNumbers.AsQueryable().SingleOrDefault(); + int pageNumber1 = pageNumbers.SingleOrDefault(); if (pageNumber1 == 0) { pageNumber1 = 1; @@ -2207,7 +2239,7 @@ static void SingleOrDefaultEx3() Console.WriteLine("The value of the pageNumber1 variable is {0}", pageNumber1); // Setting the default value to 1 by using DefaultIfEmpty() in the query. - int pageNumber2 = pageNumbers.AsQueryable().DefaultIfEmpty(1).Single(); + int pageNumber2 = pageNumbers.DefaultIfEmpty(1).Single(); Console.WriteLine("The value of the pageNumber2 variable is {0}", pageNumber2); /* @@ -2229,12 +2261,14 @@ static void SkipEx1() // Sort the grades in descending order and // get all except the first three. - IEnumerable lowerGrades = grades.AsQueryable() + IEnumerable lowerGrades = grades .OrderByDescending(g => g).Skip(3); Console.WriteLine("All grades except the top three are:"); foreach (int grade in lowerGrades) + { Console.WriteLine(grade); + } /* This code produces the following output: @@ -2261,13 +2295,15 @@ static void SkipWhileEx1() // taking all the grades after the first grade // that is less than 80. IEnumerable lowerGrades = - grades.AsQueryable() + grades .OrderByDescending(grade => grade) .SkipWhile(grade => grade >= 80); Console.WriteLine("All grades below 80:"); foreach (int grade in lowerGrades) + { Console.WriteLine(grade); + } /* This code produces the following output: @@ -2290,12 +2326,13 @@ static void SkipWhileEx2() // Skip over amounts in the array until the first amount // that is less than or equal to the product of its // index in the array and 1000. Take the remaining items. - IEnumerable query = - amounts.AsQueryable() + IEnumerable query = amounts .SkipWhile((amount, index) => amount > index * 1000); foreach (int amount in query) + { Console.WriteLine(amount); + } /* This code produces the following output: @@ -2315,7 +2352,7 @@ static void SumEx1() // List numbers = [43.68F, 1.25F, 583.7F, 6.5F]; - float sum = numbers.AsQueryable().Sum(); + float sum = numbers.Sum(); Console.WriteLine("The sum of the numbers is {0}.", sum); @@ -2333,7 +2370,7 @@ static void SumEx2() // float?[] points = [null, 0, 92.83F, null, 100.0F, 37.46F, 81.1F]; - float? sum = points.AsQueryable().Sum(); + float? sum = points.Sum(); Console.WriteLine("Total points earned: {0}", sum); @@ -2349,22 +2386,22 @@ static void SumEx2() static class Sum3 { // - class Package + class Package(string company, double weight) { - public string Company { get; set; } - public double Weight { get; set; } + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; } public static void SumEx3() { List packages = - [ new Package { Company = "Coho Vineyard", Weight = 25.2 }, - new Package { Company = "Lucerne Publishing", Weight = 18.7 }, - new Package { Company = "Wingtip Toys", Weight = 6.0 }, - new Package { Company = "Adventure Works", Weight = 33.8 } ]; + [ new Package ("Coho Vineyard", 25.2 ), + new Package ("Lucerne Publishing", 18.7 ), + new Package ("Wingtip Toys", 6.0 ), + new Package ("Adventure Works", 33.8 ) ]; // Calculate the sum of all package weights. - double totalWeight = packages.AsQueryable() + double totalWeight = packages .Sum(pkg => pkg.Weight); Console.WriteLine("The total weight of the packages is: {0}", totalWeight); @@ -2387,12 +2424,14 @@ static void TakeEx1() int[] grades = [59, 82, 70, 56, 92, 98, 85]; // Sort the grades in descending order and take the first three. - IEnumerable topThreeGrades = grades.AsQueryable() + IEnumerable topThreeGrades = grades .OrderByDescending(grade => grade).Take(3); Console.WriteLine("The top three grades are:"); foreach (int grade in topThreeGrades) + { Console.WriteLine(grade); + } /* This code produces the following output: @@ -2416,12 +2455,13 @@ static void TakeWhileEx1() // Take strings from the array until a string // that is equal to "orange" is found. - IEnumerable query = - fruits.AsQueryable() + IEnumerable query = fruits .TakeWhile(fruit => string.Compare("orange", fruit, true) != 0); foreach (string fruit in query) + { Console.WriteLine(fruit); + } /* This code produces the following output: @@ -2442,12 +2482,13 @@ static void TakeWhileEx2() // Take strings from the array until a string whose length // is less than its index in the array is found. - IEnumerable query = - fruits.AsQueryable() + IEnumerable query = fruits .TakeWhile((fruit, index) => fruit.Length >= index); foreach (string fruit in query) + { Console.WriteLine(fruit); + } /* This code produces the following output: @@ -2473,12 +2514,14 @@ static void ThenByEx1() // Sort the strings first by their length and then // alphabetically by passing the identity selector function. - IEnumerable query = fruits.AsQueryable() + IEnumerable query = fruits .OrderBy(fruit => fruit.Length) .ThenBy(fruit => fruit); foreach (string fruit in query) + { Console.WriteLine(fruit); + } /* This code produces the following output: @@ -2508,13 +2551,14 @@ public static void ThenByDescendingEx1() // Sort the strings first ascending by their length and // then descending using a custom case insensitive comparer. - IEnumerable query = - fruits.AsQueryable() + IEnumerable query = fruits .OrderBy(fruit => fruit.Length) .ThenByDescending(fruit => fruit, StringComparer.OrdinalIgnoreCase); foreach (string fruit in query) + { Console.WriteLine(fruit); + } } /* @@ -2542,10 +2586,12 @@ static void UnionEx1() int[] ints2 = [8, 3, 6, 4, 4, 9, 1, 0]; // Get the set union of the items in the two arrays. - IEnumerable union = ints1.AsQueryable().Union(ints2); + IEnumerable union = ints1.Union(ints2); foreach (int num in union) + { Console.Write("{0} ", num); + } /* This code produces the following output: @@ -2568,11 +2614,13 @@ static void WhereEx1() "orange", "blueberry", "grape", "strawberry" ]; // Get all strings whose length is less than 6. - IEnumerable query = fruits.AsQueryable() + IEnumerable query = fruits .Where(fruit => fruit.Length < 6); foreach (string fruit in query) + { Console.WriteLine(fruit); + } /* This code produces the following output: @@ -2592,12 +2640,13 @@ static void WhereEx2() // Get all the numbers that are less than or equal to // the product of their index in the array and 10. - IEnumerable query = - numbers.AsQueryable() + IEnumerable query = numbers .Where((number, index) => number <= index * 10); foreach (int number in query) + { Console.WriteLine(number); + } /* This code produces the following output: @@ -2619,11 +2668,13 @@ static void ZipEx() int[] numbers = [1, 2, 3, 4]; string[] words = ["one", "two", "three"]; - IQueryable numbersAndWords = numbers.AsQueryable() + var numbersAndWords = numbers .Zip(words, (first, second) => first + " " + second); foreach (string item in numbersAndWords) + { Console.WriteLine(item); + } // This code produces the following output: diff --git a/snippets/csharp/System.Linq/README.txt b/snippets/csharp/System.Linq/README.txt new file mode 100644 index 00000000000..f992bcd2ae3 --- /dev/null +++ b/snippets/csharp/System.Linq/README.txt @@ -0,0 +1,9 @@ +1. the LINQ docs C# samples [in GitHub repo] consist of 6 projects to showcase IEnumerable and IQueryable +unfortunately much code unecessarily invokes AsQueryable despite simpler IEnumerable method implementations existing +- [thus such guidance is poor as such AsQueryable () can be avoided] +2. should update to useful modern C# v12 semantics [Primary constructors, Collection expressions, Span, is, etc] +3. calls made to default parameterless ctor then assigning individual properties, rather than using parameterised ctors explicitly +- or better yet primary constructor +4. current analyzers also disclose numerous Warnings/Messages, emphasising poor guidance for today's coding +5. many cases of wastefully using Any(),Count(),LongCount etc when optimal coding available (e.g. Count, Length for Collections). +6. spurious ToString() call in OrderByIComparer() [line #1804] From 01d885d81ead8d55ae14abf7d8ab9d5d81be2ef8 Mon Sep 17 00:00:00 2001 From: DickBaker Date: Mon, 15 Jul 2024 16:50:01 +0100 Subject: [PATCH 4/8] mid715 --- .../Enumerable/AggregateTSource/enumerable.cs | 395 +++++++-------- .../Enumerable/Comparers/CustomComparer.cs | 53 +- .../Comparers/EncapsulatedComparer.cs | 38 +- .../ILookupTKey,TElement/Overview/ILookup.cs | 12 +- .../Queryable/AggregateTSource/queryable.cs | 477 +++++++++--------- 5 files changed, 481 insertions(+), 494 deletions(-) diff --git a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs index 3cfc3c64acd..fdf72d488de 100644 --- a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs +++ b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs @@ -83,9 +83,10 @@ class Pet(string name, int age) public static void AllEx() { // Create an array of Pets. - Pet[] pets = [ new ("Barley", 10 ), - new ("Boots", 4 ), - new ("Whiskers", 6 ) ]; + Pet[] pets = [ + new ("Barley", 10 ), + new ("Boots", 4 ), + new ("Whiskers", 6 ) ]; // Determine whether all pet names // in the array start with 'B'. @@ -105,7 +106,7 @@ public static void AllEx() static class All2 { // - class Pet (string name, int age) + class Pet(string name, int age) { public string Name { get; set; } = name; public int Age { get; set; } = age; @@ -118,19 +119,16 @@ class Person(string lastName, Pet[] pets) public static void AllEx2() { - List people = - [ new Person ("Haas", - [ new ("Barley", 10 ), - new ("Boots", 14 ), - new ("Whiskers", 6 )]), - new Person ("Fakhouri", - [new ("Snowball", 1)]), - new Person ("Antebi", - [new ("Belle", 8)]), - new Person ("Philips", - [ new ("Sweetie", 2), - new ("Rover", 13)] ) - ]; + List people = [ + new ("Haas", [ + new ("Barley", 10 ), + new ("Boots", 14 ), + new ("Whiskers", 6 ) ]), + new ("Fakhouri", [ new ("Snowball", 1) ]), + new ("Antebi", [ new ("Belle", 8) ]), + new ("Philips", [ + new ("Sweetie", 2), + new ("Rover", 13) ] ) ]; // Determine which people have pets that are all older than 5. IEnumerable names = from person in people @@ -185,18 +183,16 @@ class Person(string lastName, Pet[] pets) public static void AnyEx2() { - List people = - [ new Person ("Haas", - [ new ("Barley", 10 ), - new ("Boots", 14 ), - new ("Whiskers", 6 )]), - new Person ("Fakhouri", - [new ("Snowball", 1)]), - new Person ("Antebi", - []), - new Person ("Philips", - [ new ("Sweetie", 2), - new ("Rover", 13)] ) + List people = [ + new ("Haas", [ + new ("Barley", 10 ), + new ("Boots", 14 ), + new ("Whiskers", 6 ) ]), + new ("Fakhouri", [ new ("Snowball", 1) ]), + new ("Antebi", []), + new ("Philips", [ + new ("Sweetie", 2), + new ("Rover", 13) ] ) ]; // Determine which people have a non-empty Pet array. @@ -232,10 +228,10 @@ class Pet(string name, int age, bool vaccinated) public static void AnyEx3() { // Create an array of Pets. - Pet[] pets = - [ new ("Barley", 8, true ), - new ("Boots", 4, false ), - new ("Whiskers", 1, false ) ]; + Pet[] pets = [ + new ("Barley", 8, true ), + new ("Boots", 4, false ), + new ("Whiskers", 1, false ) ]; // Determine whether any pets over age 1 are also unvaccinated. bool unvaccinated = @@ -402,17 +398,19 @@ class Pet(string name, int age) static Pet[] GetCats() { - Pet[] cats = [ new ("Barley", 8 ), - new ("Boots", 4 ), - new ("Whiskers", 1 ) ]; + Pet[] cats = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; return cats; } static Pet[] GetDogs() { - Pet[] dogs = [ new ("Bounder", 3 ), - new ("Snoopy", 14 ), - new ("Fido", 9 ) ]; + Pet[] dogs = [ + new ("Bounder", 3 ), + new ("Snoopy", 14 ), + new ("Fido", 9 ) ]; return dogs; } @@ -519,18 +517,19 @@ static void CountEx1() static class Count { - // - class Pet(string name, bool vaccinated) - { - public string Name { get; set; } = name; - public bool Vaccinated { get; set; } = vaccinated; - } + // + class Pet(string name, bool vaccinated) + { + public string Name { get; set; } = name; + public bool Vaccinated { get; set; } = vaccinated; + } public static void CountEx2() { - Pet[] pets = [ new ("Barley", true ), - new ("Boots", false ), - new ("Whiskers", false ) ]; + Pet[] pets = [ + new ("Barley", true ), + new ("Boots", false ), + new ("Whiskers", false ) ]; try { @@ -563,10 +562,10 @@ class Pet(string name, int age) public static void DefaultIfEmptyEx1() { - List pets = - [ new ("Barley", 8 ), - new ("Boots", 4 ), - new ("Whiskers", 1 ) ]; + List pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; foreach (var pet in pets.DefaultIfEmpty()) { @@ -615,10 +614,10 @@ public static void DefaultIfEmptyEx2() { Pet defaultPet = new("Default Pet", 0); - List pets1 = - [ new ("Barley", 8 ), - new ("Boots", 4 ), - new ("Whiskers", 1 ) ]; + List pets1 = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; foreach (Pet pet in pets1.DefaultIfEmpty(defaultPet)) { @@ -678,9 +677,7 @@ static void DistinctEx1() static void ElementAtEx1() { // - string[] names = - [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - + string[] names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu" ]; Random random = new(DateTime.Now.Millisecond); @@ -701,9 +698,8 @@ static void ElementAtEx1() static void ElementAtOrDefaultEx1() { // - string[] names = - [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" ]; + string[] names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", + "Hedlund, Magnus", "Ito, Shu" ]; const int index = 20; @@ -919,11 +915,11 @@ class Pet(string name, int age) public static void GroupByEx1() { // Create a list of pets. - List pets = - [ new ("Barley", 8 ), - new ("Boots", 4 ), - new ("Whiskers", 1 ), - new ("Daisy", 4 ) ]; + List pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ), + new ("Daisy", 4 ) ]; // Group the pets using Age as the key value // and selecting only the pet's Name for each value. @@ -961,11 +957,11 @@ public static void GroupByEx1() public static void GroupByEx2() { // Create a list of pets. - List pets = - [ new ("Barley", 8 ), - new ("Boots", 4 ), - new ("Whiskers", 1 ), - new ("Daisy", 4 ) ]; + List pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ), + new ("Daisy", 4 ) ]; // Group the pets using Age as the key value // and selecting only the pet's name for each value. @@ -1002,11 +998,11 @@ class Pet(string name, float age) public static void GroupByEx3() { // Create a list of pets. - List petsList = - [ new ("Barley", 8.3f ), - new ("Boots", 4.9f ), - new ("Whiskers", 1.5f ), - new ("Daisy", 4.3f ) ]; + List petsList = [ + new ("Barley", 8.3f ), + new ("Boots", 4.9f ), + new ("Whiskers", 1.5f ), + new ("Daisy", 4.3f ) ]; // Group Pet objects by the Math.Floor of their age. // Then project an anonymous type from each group @@ -1065,11 +1061,11 @@ class Pet(string name, float age) public static void GroupByEx4() { // Create a list of pets. - List petsList = - [ new ("Barley", 8.3f ), - new ("Boots", 4.9f ), - new ("Whiskers", 1.5f ), - new ("Daisy", 4.3f ) ]; + List petsList = [ + new ("Barley", 8.3f ), + new ("Boots", 4.9f ), + new ("Whiskers", 1.5f ), + new ("Daisy", 4.3f ) ]; // Group Pet.Age values by the Math.Floor of the age. // Then project an anonymous type from each group @@ -1134,14 +1130,14 @@ class Pet(string name, Person owner) public static void GroupJoinEx1() { - Person magnus = new("Hedlund, Magnus" ); - Person terry = new("Adams, Terry" ); - Person charlotte = new("Weiss, Charlotte" ); + Person magnus = new("Hedlund, Magnus"); + Person terry = new("Adams, Terry"); + Person charlotte = new("Weiss, Charlotte"); - Pet barley = new("Barley", terry ); - Pet boots = new("Boots", terry ); - Pet whiskers = new("Whiskers", charlotte ); - Pet daisy = new("Daisy", magnus ); + Pet barley = new("Barley", terry); + Pet boots = new("Boots", terry); + Pet whiskers = new("Whiskers", charlotte); + Pet daisy = new("Daisy", magnus); List people = [magnus, terry, charlotte]; List pets = [barley, boots, whiskers, daisy]; @@ -1188,14 +1184,14 @@ public static void GroupJoinEx1() // Uses query syntax. public static void GroupJoinEx2() { - Person magnus = new("Hedlund, Magnus" ); - Person terry = new("Adams, Terry" ); - Person charlotte = new("Weiss, Charlotte" ); + Person magnus = new("Hedlund, Magnus"); + Person terry = new("Adams, Terry"); + Person charlotte = new("Weiss, Charlotte"); - Pet barley = new("Barley", terry ); - Pet boots = new("Boots", terry ); - Pet whiskers = new("Whiskers", charlotte ); - Pet daisy = new("Daisy", magnus ); + Pet barley = new("Barley", terry); + Pet boots = new("Boots", terry); + Pet whiskers = new("Whiskers", charlotte); + Pet daisy = new("Daisy", magnus); List people = [magnus, terry, charlotte]; List pets = [barley, boots, whiskers, daisy]; @@ -1267,14 +1263,14 @@ class Pet(string name, Person owner) public static void JoinEx1() { - Person magnus = new ("Hedlund, Magnus" ); - Person terry = new("Adams, Terry" ); - Person charlotte = new("Weiss, Charlotte" ); + Person magnus = new("Hedlund, Magnus"); + Person terry = new("Adams, Terry"); + Person charlotte = new("Weiss, Charlotte"); - Pet barley = new("Barley", terry ); - Pet boots = new("Boots", terry ); - Pet whiskers = new("Whiskers", charlotte ); - Pet daisy = new("Daisy", magnus ); + Pet barley = new("Barley", terry); + Pet boots = new("Boots", terry); + Pet whiskers = new("Whiskers", charlotte); + Pet daisy = new("Daisy", magnus); List people = [magnus, terry, charlotte]; List pets = [barley, boots, whiskers, daisy]; @@ -1445,9 +1441,10 @@ class Pet(string name, int age) public static void LongCountEx2() { - Pet[] pets = [ new ("Barley", 8 ), - new ("Boots", 4 ), - new ("Whiskers", 1 ) ]; + Pet[] pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; const int Age = 3; @@ -1536,9 +1533,10 @@ public int CompareTo(Pet? other) public static void MaxEx3() { - Pet[] pets = [ new ("Barley", age:8 ), - new ("Boots", age:4 ), - new ("Whiskers", age:1 ) ]; + Pet[] pets = [ + new ("Barley", age:8 ), + new ("Boots", age:4 ), + new ("Whiskers", age:1 ) ]; //if (pets.Length > 0) { @@ -1571,9 +1569,10 @@ class Pet(string name, int age) public static void MaxEx4() { - Pet[] pets = [ new ("Barley", 8 ), - new ("Boots", 4 ), - new ("Whiskers", 1 ) ]; + Pet[] pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; int max = pets.Max(pet => pet.Age + pet.Name.Length); @@ -1634,7 +1633,7 @@ static class Min9 // IEnumerable /// This class implements IComparable in order to /// be able to compare different Pet objects. /// - class Pet (string name , int age): IComparable + class Pet(string name, int age) : IComparable { public string Name { get; set; } = name; public int Age { get; set; } = age; @@ -1655,9 +1654,10 @@ public int CompareTo(Pet? other) => public static void MinEx3() { - Pet[] pets = [ new ("Barley", 8 ), - new ("Boots", 4 ), - new ("Whiskers", 1 ) ]; + Pet[] pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; var min = pets.Min(p => p.Age); var youngest = pets.First(p => p.Age == min); @@ -1686,9 +1686,10 @@ class Pet(string name, int age) public static void MinEx4() { - Pet[] pets = [ new ("Barley", 8 ), - new ("Boots", 4 ), - new ("Whiskers", 1 ) ]; + Pet[] pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; var min = pets.Min(pet => pet.Age); @@ -1708,15 +1709,13 @@ The youngest animal is age 1. static void OfTypeEx1() { // - System.Collections.ArrayList fruits = - [ + System.Collections.ArrayList fruits = [ "Mango", "Orange", null, "Apple", 3.0, - "Banana" - ]; + "Banana" ]; // Apply OfType() to the ArrayList. IEnumerable query1 = fruits.OfType(); @@ -1767,9 +1766,10 @@ class Pet(string name, int age) public static void OrderByEx1() { - Pet[] pets = [ new ("Barley", 8 ), - new ("Boots", 4 ), - new ("Whiskers", 1 ) ]; + Pet[] pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; IEnumerable query = pets.OrderBy(pet => pet.Age); @@ -1898,8 +1898,7 @@ public int Compare(decimal d1, decimal d2) public static void OrderByDescendingEx1() { - List decimals = - [6.2m, 8.3m, 0.5m, 1.3m, 6.3m, 9.7m]; + List decimals = [6.2m, 8.3m, 0.5m, 1.3m, 6.3m, 9.7m]; IEnumerable query = decimals.OrderByDescending(num => @@ -2083,13 +2082,10 @@ class PetOwner(string name, List pets) public static void SelectManyEx1() { - PetOwner[] petOwners = - [ new ("Higa, Sidney", - ["Scruffy", "Sam"] ), - new ("Ashkenazi, Ronen", - ["Walker", "Sugar"] ), - new ("Price, Vernette", - ["Scratches", "Diesel"] ) ]; + PetOwner[] petOwners = [ + new ("Higa, Sidney", ["Scruffy", "Sam"] ), + new ("Ashkenazi, Ronen", ["Walker", "Sugar"] ), + new ("Price, Vernette", ["Scratches", "Diesel"] ) ]; // Query using SelectMany(). IEnumerable query1 = petOwners.SelectMany(petOwner => petOwner.Pets); @@ -2111,9 +2107,8 @@ public static void SelectManyEx1() Console.WriteLine("\nUsing Select():"); - // Notice that two foreach loops are required to - // iterate through the results - // because the query returns a collection of arrays. + // Notice that two foreach loops are required to iterate through + // the results because the query returns a collection of arrays. foreach (List petList in query2) { foreach (string pet in petList) @@ -2159,15 +2154,11 @@ class PetOwner(string name, List pets) public static void SelectManyEx2() { - PetOwner[] petOwners = - [ new ("Higa, Sidney", - ["Scruffy", "Sam"] ), - new ("Ashkenazi, Ronen", - ["Walker", "Sugar"] ), - new ("Price, Vernette", - ["Scratches", "Diesel"] ), - new ("Hines, Patrick", - ["Dusty"] ) ]; + PetOwner[] petOwners = [ + new ("Higa, Sidney", ["Scruffy", "Sam"] ), + new ("Ashkenazi, Ronen", ["Walker", "Sugar"] ), + new ("Price, Vernette", ["Scratches", "Diesel"] ), + new ("Hines, Patrick", ["Dusty"] ) ]; // Project the items in the array by appending the index // of each PetOwner to each pet's name in that petOwner's @@ -2205,15 +2196,11 @@ class PetOwner(string name, List pets) public static void SelectManyEx3() { - PetOwner[] petOwners = - [ new ("Higa", - ["Scruffy", "Sam"] ), - new ("Ashkenazi", - ["Walker", "Sugar"] ), - new ("Price", - ["Scratches", "Diesel"] ), - new ("Hines", - ["Dusty"] ) ]; + PetOwner[] petOwners = [ + new ("Higa", ["Scruffy", "Sam"] ), + new ("Ashkenazi", ["Walker", "Sugar"] ), + new ("Price", ["Scratches", "Diesel"] ), + new ("Hines", ["Dusty"] ) ]; // Project the pet owner's name and the pet's name. var query = petOwners @@ -2257,8 +2244,8 @@ class Pet(string name, int age) public static void SequenceEqualEx1() { - Pet pet1 = new("Turbo", 2 ); - Pet pet2 = new("Peanut", 8 ); + Pet pet1 = new("Turbo", 2); + Pet pet2 = new("Peanut", 8); // Create two lists of pets. List pets1 = [pet1, pet2]; @@ -2281,23 +2268,23 @@ The lists are equal. static class SequenceEqual2 { - // - class Pet(string name, int age) - { - public string Name { get; set; } = name; - public int Age { get; set; } = age; - } + // + class Pet(string name, int age) + { + public string Name { get; set; } = name; + public int Age { get; set; } = age; + } - public static void SequenceEqualEx2() + public static void SequenceEqualEx2() { - Pet pet1 = new("Turbo", 2 ); - Pet pet2 = new("Peanut", 8 ); + Pet pet1 = new("Turbo", 2); + Pet pet2 = new("Peanut", 8); // Create two lists of pets. List pets1 = [pet1, pet2]; - List pets2 = - [ new ( "Turbo", 2 ), - new ( "Peanut", 8 ) ]; + List pets2 = [ + new ( "Turbo", 2 ), + new ( "Peanut", 8 ) ]; bool equal = pets1.SequenceEqual(pets2); @@ -2381,7 +2368,7 @@ static void SingleEx2() } catch (System.InvalidOperationException) { - Console.WriteLine("The collection does not contain exactly\n"+ + Console.WriteLine("The collection does not contain exactly\n" + "one element whose length is greater than 15."); } @@ -2574,11 +2561,11 @@ class Package(string company, double weight) public static void SumEx1() { - List packages = - [ new ("Coho Vineyard", 25.2 ), - new ("Lucerne Publishing", 18.7 ), - new ("Wingtip Toys", 6.0 ), - new ("Adventure Works", 33.8 ) ]; + List packages = [ + new ("Coho Vineyard", 25.2 ), + new ("Lucerne Publishing", 18.7 ), + new ("Wingtip Toys", 6.0 ), + new ("Adventure Works", 33.8 ) ]; double totalWeight = packages.Sum(pkg => pkg.Weight); @@ -2791,11 +2778,11 @@ class Package(string company, double weight) public static void ToArrayEx1() { - List packages = - [ new ("Coho Vineyard", 25.2 ), - new ("Lucerne Publishing", 18.7 ), - new ("Wingtip Toys", 6.0 ), - new ("Adventure Works", 33.8 ) ]; + List packages = [ + new ("Coho Vineyard", 25.2 ), + new ("Lucerne Publishing", 18.7 ), + new ("Wingtip Toys", 6.0 ), + new ("Adventure Works", 33.8 ) ]; string[] companies = packages.Select(pkg => pkg.Company).ToArray(); @@ -2821,21 +2808,21 @@ Adventure Works // overloads call each other static class ToDictionary { - // - class Package(string company, double weight, long trackingNumber) - { - public string Company { get; set; } = company; - public double Weight { get; set; } = weight; - public long TrackingNumber { get; set; } = trackingNumber; - } + // + class Package(string company, double weight, long trackingNumber) + { + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; + public long TrackingNumber { get; set; } = trackingNumber; + } public static void ToDictionaryEx1() { - List packages = - [ new ("Coho Vineyard", 25.2, 89453312L ), - new ("Lucerne Publishing", 18.7, 89112755L ), - new ("Wingtip Toys", 6.0, 299456122L ), - new ("Adventure Works", 33.8, 4665518773L ) ]; + List packages = [ + new ("Coho Vineyard", 25.2, 89453312L ), + new ("Lucerne Publishing", 18.7, 89112755L ), + new ("Wingtip Toys", 6.0, 299456122L ), + new ("Adventure Works", 33.8, 4665518773L ) ]; // Create a Dictionary of Package objects, // using TrackingNumber as the key. @@ -2909,17 +2896,12 @@ class Package(string company, double weight, long trackingNumber) public static void ToLookupEx1() { // Create a list of Packages. - List packages = - [ new ("Coho Vineyard", - 25.2, 89453312L ), - new ("Lucerne Publishing", - 18.7, 89112755L ), - new ("Wingtip Toys", - 6.0, 299456122L ), - new ("Contoso Pharmaceuticals", - 9.3, 670053128L ), - new ("Wide World Importers", - 33.8, 4665518773L ) ]; + List packages = [ + new ("Coho Vineyard", 25.2, 89453312L ), + new ("Lucerne Publishing", 18.7, 89112755L ), + new ("Wingtip Toys", 6.0, 299456122L ), + new ("Contoso Pharmaceuticals", 9.3, 670053128L ), + new ("Wide World Importers", 33.8, 4665518773L ) ]; // Create a Lookup to organize the packages. // Use the first character of Company as the key value. @@ -2988,9 +2970,8 @@ 5 3 9 7 8 6 4 1 0 static void WhereEx1() { // - List fruits = - [ "apple", "passionfruit", "banana", "mango", - "orange", "blueberry", "grape", "strawberry" ]; + List fruits = [ "apple", "passionfruit", "banana", "mango", + "orange", "blueberry", "grape", "strawberry" ]; IEnumerable query = fruits.Where(fruit => fruit.Length < 6); diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs b/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs index 41d0e5116a7..f456b67b614 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs @@ -48,11 +48,13 @@ static class Program static void Main() { // - Product[] store1 = [ new("apple",9 ), - new("orange",4 ) ]; + Product[] store1 = [ + new("apple",9 ), + new("orange",4 ) ]; - Product[] store2 = [ new("apple",9 ), - new("lemon",12 ) ]; + Product[] store2 = [ + new("apple",9 ), + new("lemon",12 ) ]; // Get the products from the first array // that have duplicates in the second array. @@ -72,11 +74,13 @@ apple 9 // // - Product[] store10 = [ new("apple",9 ), - new("orange",4 ) ]; + Product[] store10 = [ + new("apple",9 ), + new("orange",4 ) ]; - Product[] store20 = [ new("apple",9 ), - new("lemon",12 ) ]; + Product[] store20 = [ + new("apple",9 ), + new("lemon",12 ) ]; //Get the products from the both arrays //excluding duplicates. @@ -99,10 +103,11 @@ lemon 12 // // - Product[] products = [ new("apple",9 ), - new("orange",4 ), - new("apple",9 ), - new("lemon",12 ) ]; + Product[] products = [ + new("apple",9 ), + new("orange",4 ), + new("apple",9 ), + new("lemon",12 ) ]; // Exclude duplicates. @@ -123,9 +128,10 @@ lemon 12 // // - Product[] fruits = [ new("apple",9 ), - new("orange",4 ), - new("lemon",12 ) ]; + Product[] fruits = [ + new("apple",9 ), + new("orange",4 ), + new("lemon",12 ) ]; Product apple = new("apple", 9); Product kiwi = new("kiwi", 8); @@ -148,9 +154,10 @@ lemon 12 // // - Product[] fruits1 = [ new("apple",9 ), - new("orange",4 ), - new("lemon",12 ) ]; + Product[] fruits1 = [ + new("apple",9 ), + new("orange",4 ), + new("lemon",12 ) ]; Product[] fruits2 = [new("apple", 9)]; @@ -176,11 +183,13 @@ lemon 12 // - Product[] storeA = [ new("apple",9 ), - new("orange",4 ) ]; + Product[] storeA = [ + new("apple",9 ), + new("orange",4 ) ]; - Product[] storeB = [ new("apple",9 ), - new("orange",4 ) ]; + Product[] storeB = [ + new("apple",9 ), + new("orange",4 ) ]; var equalAB = storeA.SequenceEqual(storeB, new ProductComparer()); diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs b/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs index e5a323e615d..5bb3ef368c4 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs @@ -49,11 +49,13 @@ static void Main() // Some samples here need to use ProductA in conjunction with // ProductComparer, which implements IEqualityComparer (not IEquatable). // - ProductA[] store1 = [ new("apple", 9 ), - new("orange", 4 ) ]; + ProductA[] store1 = [ + new("apple", 9 ), + new("orange", 4 ) ]; - ProductA[] store2 = [ new("apple", 9 ), - new("lemon", 12 ) ]; + ProductA[] store2 = [ + new("apple", 9 ), + new("lemon", 12 ) ]; // // @@ -96,10 +98,11 @@ lemon 12 // // - MyProduct[] products = [ new("apple", 9 ), - new("orange", 4 ), - new("apple", 9 ), - new("lemon", 12 ) ]; + MyProduct[] products = [ + new("apple", 9 ), + new("orange", 4 ), + new("apple", 9 ), + new("lemon", 12 ) ]; // Exclude duplicates. @@ -120,11 +123,12 @@ lemon 12 // // - ProductA[] fruits1 = [ new("apple", 9 ), - new("orange", 4 ), - new("lemon", 12 ) ]; + ProductA[] fruits1 = [ + new("apple", 9 ), + new("orange", 4 ), + new("lemon", 12 ) ]; - ProductA[] fruits2 = [new("apple", 9 )]; + ProductA[] fruits2 = [new("apple", 9)]; // Get all the elements from the first array // except for the elements from the second array. @@ -147,11 +151,13 @@ lemon 12 // - ProductA[] storeA = [ new("apple", 9 ), - new("orange", 4 ) ]; + ProductA[] storeA = [ + new("apple", 9 ), + new("orange", 4 ) ]; - ProductA[] storeB = [ new("apple", 9 ), - new("orange", 4 ) ]; + ProductA[] storeB = [ + new("apple", 9 ), + new("orange", 4 ) ]; var equalAB = storeA.SequenceEqual(storeB); diff --git a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs index 2ae985202df..7cd60d30352 100644 --- a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs +++ b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs @@ -19,12 +19,12 @@ class Package(string company, double weight, long trackingNumber) public static void ILookupExample() { // Create a list of Packages to put into an ILookup data structure. - List packages = - [ new Package ("Coho Vineyard", 25.2, 89453312L ), - new Package ("Lucerne Publishing", 18.7, 89112755L ), - new Package ("Wingtip Toys", 6.0, 299456122L ), - new Package ("Contoso Pharmaceuticals", 9.3, 670053128L ), - new Package ("Wide World Importers", 33.8, 4665518773L ) ]; + List packages = [ + new Package ("Coho Vineyard", 25.2, 89453312L ), + new Package ("Lucerne Publishing", 18.7, 89112755L ), + new Package ("Wingtip Toys", 6.0, 299456122L ), + new Package ("Contoso Pharmaceuticals", 9.3, 670053128L ), + new Package ("Wide World Importers", 33.8, 4665518773L ) ]; // Create a Lookup to organize the packages. Use the first character of Company as the key value. // Select Company appended to TrackingNumber for each element value in the ILookup object. diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs b/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs index 6260045d6af..ee388ef44c4 100644 --- a/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs +++ b/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs @@ -87,18 +87,19 @@ static void AggregateEx3() public static class All { // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void AllEx1() { // Create an array of Pets. - Pet[] pets = [ new() { Name="Barley", Age=10 }, - new() { Name="Boots", Age=4 }, - new() { Name="Whiskers", Age=6 } ]; + Pet[] pets = [ + new ("Barley",10 ), + new ("Boots",4 ), + new ("Whiskers",6 ) ]; // Determine whether all pet names in the array start with 'B'. bool allStartWithB = @@ -119,32 +120,29 @@ public static void AllEx1() static class All2 { // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } - class Person + class Person(string lastName, Pet[] pets) { - public required string LastName { get; set; } - public required Pet[] Pets { get; set; } + public string LastName { get; set; } = lastName; + public Pet[] Pets { get; set; } = pets; } public static void AllEx2() { - List people = - [ new Person { LastName = "Haas", - Pets = [ new() { Name="Barley", Age=10 }, - new() { Name="Boots", Age=14 }, - new() { Name="Whiskers", Age=6 }]}, - new Person { LastName = "Fakhouri", - Pets = [new() { Name = "Snowball", Age = 1}]}, - new Person { LastName = "Antebi", - Pets = [new() { Name = "Belle", Age = 8}]}, - new Person { LastName = "Philips", - Pets = [ new() { Name = "Sweetie", Age = 2}, - new() { Name = "Rover", Age = 13}] } - ]; + List people = [ + new ("Haas", [ + new ("Barley",10 ), + new ("Boots",14 ), + new ("Whiskers",6 ) ]), + new("Fakhouri", [ new("Snowball", 1) ]), + new("Antebi", [ new("Belle", 8) ]), + new ("Philips", [ + new("Sweetie", 2), + new("Rover", 13) ] ) ]; // Determine which people have pets that are all older than 5. IEnumerable names = from person in people @@ -188,31 +186,29 @@ public static void AnyEx1() } // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } - class Person + class Person(string lastName, Pet[] pets) { - public required string LastName { get; set; } - public required Pet[] Pets { get; set; } + public string LastName { get; set; } = lastName; + public Pet[] Pets { get; set; } = pets; } public static void AnyEx2() { - List people = - [ new Person { LastName = "Haas", - Pets = [ new() { Name="Barley", Age=10 }, - new() { Name="Boots", Age=14 }, - new() { Name="Whiskers", Age=6 }]}, - new Person { LastName = "Fakhouri", - Pets = [new() { Name = "Snowball", Age = 1}]}, - new Person { LastName = "Antebi", - Pets = []}, - new Person { LastName = "Philips", - Pets = [ new() { Name = "Sweetie", Age = 2}, - new() { Name = "Rover", Age = 13}] } + List people = [ + new ("Haas", [ + new ("Barley",10 ), + new ("Boots",14 ), + new ("Whiskers",6 ) ]), + new("Fakhouri", [ new("Snowball", 1) ]), + new("Antebi",[]), + new("Philips", [ + new("Sweetie", 2), + new("Rover", 13) ] ) ]; // Determine which people have a non-empty Pet array. @@ -234,24 +230,23 @@ where person.Pets.Any() // [CA1860] better to use "where person.Pets.Length != 0 } // } - static class Any2 { // - class Pet + public class Pet(string name, int age, bool vaccinated) { - public required string Name { get; set; } - public int Age { get; set; } - public bool Vaccinated { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; + public bool Vaccinated { get; set; } = vaccinated; } public static void AnyEx3() { // Create an array of Pet objects. - Pet[] pets = - [ new() { Name="Barley", Age=8, Vaccinated=true }, - new() { Name="Boots", Age=4, Vaccinated=false }, - new() { Name="Whiskers", Age=1, Vaccinated=false } ]; + Pet[] pets = [ + new ("Barley",8, true ), + new ("Boots",4, false ), + new ("Whiskers",1, false ) ]; // Determine whether any pets over age 1 are also unvaccinated. bool unvaccinated = @@ -396,11 +391,11 @@ static void CastEx2() // Cast the objects in the list to type 'string' // and project the first letter of each string. - IEnumerable query = words + var query = words .Cast() - .Select(str => str.Substring(0, 1)); + .Select(str => str[0]); - foreach (string s in query) + foreach (var s in query) { Console.WriteLine(s); } @@ -420,27 +415,29 @@ static void CastEx2() static class Concat { // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } // This method creates and returns an array of Pet objects. static Pet[] GetCats() { - Pet[] cats = [ new() { Name="Barley", Age=8 }, - new() { Name="Boots", Age=4 }, - new() { Name="Whiskers", Age=1 } ]; + Pet[] cats = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; return cats; } // This method creates and returns an array of Pet objects. static Pet[] GetDogs() { - Pet[] dogs = [ new() { Name="Bounder", Age=3 }, - new() { Name="Snoopy", Age=14 }, - new() { Name="Fido", Age=9 } ]; + Pet[] dogs = [ + new ("Bounder",3 ), + new ("Snoopy",14 ), + new ("Fido",9 ) ]; return dogs; } @@ -552,18 +549,19 @@ static void CountEx1() static class Count { // - class Pet + class Pet(string name, bool vaccinated) { - public required string Name { get; set; } - public bool Vaccinated { get; set; } + public string Name { get; set; } = name; + public bool Vaccinated { get; set; } = vaccinated; } public static void CountEx2() { // Create an array of Pet objects. - Pet[] pets = [ new() { Name="Barley", Vaccinated=true }, - new() { Name="Boots", Vaccinated=false }, - new() { Name="Whiskers", Vaccinated=false } ]; + Pet[] pets = [ + new ("Barley", true ), + new ("Boots", false ), + new ("Whiskers", false ) ]; // Count the number of unvaccinated pets in the array. int numberUnvaccinated = @@ -586,27 +584,26 @@ public static void CountEx2() static class DefaultIfEmpty1 { // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void DefaultIfEmptyEx1() { // Create a list of Pet objects. - List pets = - [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } ]; + List pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; // Call DefaultIfEmtpy() on the collection that Select() // returns, so that if the initial list is empty, there // will always be at least one item in the returned array. - string[] names = - [.. pets - .Select(pet => pet.Name) - .DefaultIfEmpty()]; + string[] names = [.. pets + .Select(pet => pet.Name) + .DefaultIfEmpty() ]; string first = names[0]; Console.WriteLine(first); @@ -623,29 +620,27 @@ public static void DefaultIfEmptyEx1a() { // // Create a list of Pet objects. - List pets = - [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } ]; + List pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; // This query selects only those pets that are 10 or older. // In case there are no pets that meet that criteria, call // DefaultIfEmpty(). This code passes an (optional) default // value to DefaultIfEmpty(). - string[] oldPets = - [.. pets + string[] oldPets = [.. pets .Where(pet => pet.Age >= 10) .Select(pet => pet.Name) - .DefaultIfEmpty("[EMPTY]")]; + .DefaultIfEmpty("[EMPTY]") ]; Console.WriteLine("First query: " + oldPets[0]); // This query selects only those pets that are 10 or older. // This code does not call DefaultIfEmpty(). - string[] oldPets2 = - [.. pets - .Where(pet => pet.Age >= 10) - .Select(pet => pet.Name)]; + string[] oldPets2 = [.. pets + .Where(pet => pet.Age >= 10) + .Select(pet => pet.Name) ]; // There may be no elements in the array, so directly // accessing element 0 may throw an exception. @@ -711,7 +706,7 @@ static void ElementAtEx1() string name = names.ElementAt(random.Next(0, names.Length)); - //names[random.Next(0, names.Length)]; // simpler + //names[random.Next(0, names.Length) ]; // simpler Console.WriteLine("The name chosen at random is '{0}'.", name); @@ -914,20 +909,20 @@ The value of the firstMonth2 variable is 1 static class GroupBy { // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void GroupByEx1() { // Create a list of Pet objects. - List pets = - [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 }, - new Pet { Name="Daisy", Age=4 } ]; + List pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ), + new ("Daisy",4 ) ]; // Group the pets using Pet.Age as the key. // Use Pet.Name as the value for each entry. @@ -956,20 +951,20 @@ public static void GroupByEx1() static class GroupBy2 { // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void GroupByEx2() { // Create a list of Pet objects. - List pets = - [ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 }, - new Pet { Name="Daisy", Age=4 } ]; + List pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ), + new ("Daisy",4 ) ]; // Group the pets using Pet.Age as the key. // Use Pet.Name as the value for each entry. @@ -1009,20 +1004,20 @@ public static void GroupByEx2() static class GroupBy3 { // - class Pet + class Pet(string name, float age) { - public required string Name { get; set; } - public double Age { get; set; } + public string Name { get; set; } = name; + public float Age { get; set; } = age; } public static void GroupByEx3() { // Create a list of pets. - List petsList = - [ new Pet { Name="Barley", Age=8.3 }, - new Pet { Name="Boots", Age=4.9 }, - new Pet { Name="Whiskers", Age=1.5 }, - new Pet { Name="Daisy", Age=4.3 } ]; + List petsList = [ + new ("Barley",8.3f ), + new ("Boots",4.9f ), + new ("Whiskers",1.5f ), + new ("Daisy",4.3f ) ]; // Group Pet objects by the Math.Floor of their age. // Then project an anonymous type from each group @@ -1072,20 +1067,20 @@ public static void GroupByEx3() static class GroupBy4 { // - class Pet + class Pet(string name, float age) { - public required string Name { get; set; } - public double Age { get; set; } + public string Name { get; set; } = name; + public float Age { get; set; } = age; } public static void GroupByEx4() { // Create a list of pets. - List petsList = - [ new Pet { Name="Barley", Age=8.3 }, - new Pet { Name="Boots", Age=4.9 }, - new Pet { Name="Whiskers", Age=1.5 }, - new Pet { Name="Daisy", Age=4.3 } ]; + List petsList = [ + new ("Barley",8.3f ), + new ("Boots",4.9f ), + new ("Whiskers",1.5f ), + new ("Daisy",4.3f ) ]; // Group Pet.Age values by the Math.Floor of the age. // Then project an anonymous type from each group @@ -1137,27 +1132,27 @@ public static void GroupByEx4() static class GroupJoin { // - class Person + class Person(string name) { - public required string Name { get; set; } + public string Name { get; set; } = name; } - class Pet + class Pet(string name, Person owner) { - public required string Name { get; set; } - public required Person Owner { get; set; } + public string Name { get; set; } = name; + public Person Owner { get; set; } = owner; } public static void GroupJoinEx1() { - Person magnus = new() { Name = "Hedlund, Magnus" }; - Person terry = new() { Name = "Adams, Terry" }; - Person charlotte = new() { Name = "Weiss, Charlotte" }; + Person magnus = new("Hedlund, Magnus"); + Person terry = new("Adams, Terry"); + Person charlotte = new("Weiss, Charlotte"); - Pet barley = new() { Name = "Barley", Owner = terry }; - Pet boots = new() { Name = "Boots", Owner = terry }; - Pet whiskers = new() { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new() { Name = "Daisy", Owner = magnus }; + Pet barley = new("Barley", terry); + Pet boots = new("Boots", terry); + Pet whiskers = new("Whiskers", charlotte); + Pet daisy = new("Daisy", magnus); List people = [magnus, terry, charlotte]; List pets = [barley, boots, whiskers, daisy]; @@ -1234,27 +1229,27 @@ static void IntersectEx1() static class Join { // - class Person + class Person(string name) { - public required string Name { get; set; } + public string Name { get; set; } = name; } - class Pet + class Pet(string name, Person owner) { - public required string Name { get; set; } - public required Person Owner { get; set; } + public string Name { get; set; } = name; + public Person Owner { get; set; } = owner; } public static void JoinEx1() { - Person magnus = new() { Name = "Hedlund, Magnus" }; - Person terry = new() { Name = "Adams, Terry" }; - Person charlotte = new() { Name = "Weiss, Charlotte" }; + Person magnus = new("Hedlund, Magnus"); + Person terry = new("Adams, Terry"); + Person charlotte = new("Weiss, Charlotte"); - Pet barley = new() { Name = "Barley", Owner = terry }; - Pet boots = new() { Name = "Boots", Owner = terry }; - Pet whiskers = new() { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new() { Name = "Daisy", Owner = magnus }; + Pet barley = new Pet("Barley", terry); + Pet boots = new("Boots", terry); + Pet whiskers = new("Whiskers", charlotte); + Pet daisy = new("Daisy", magnus); List people = [magnus, terry, charlotte]; List pets = [barley, boots, whiskers, daisy]; @@ -1439,17 +1434,18 @@ There are 6 fruits in the collection. static class LongCount { // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void LongCountEx2() { - Pet[] pets = [ new() { Name="Barley", Age=8 }, - new() { Name="Boots", Age=4 }, - new() { Name="Whiskers", Age=1 } ]; + Pet[] pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; const int Age = 3; @@ -1492,17 +1488,18 @@ The largest number is 4294967296. static class Max2 // with a selector { // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void MaxEx2() { - Pet[] pets = [ new() { Name="Barley", Age=8 }, - new() { Name="Boots", Age=4 }, - new() { Name="Whiskers", Age=1 } ]; + Pet[] pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; // Add Pet.Age to the length of Pet.Name // to determine the "maximum" Pet object in the array. @@ -1546,17 +1543,18 @@ The smallest number is -2E+103. static class Min2 // with a selector { // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void MinEx2() { - Pet[] pets = [ new() { Name="Barley", Age=8 }, - new() { Name="Boots", Age=4 }, - new() { Name="Whiskers", Age=1 } ]; + Pet[] pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; // Get the Pet object that has the smallest Age value. var min = pets.Min(pet => pet.Age); @@ -1607,17 +1605,18 @@ static void OfTypeEx1() static class OrderBy { // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void OrderByEx1() { - Pet[] pets = [ new() { Name="Barley", Age=8 }, - new() { Name="Boots", Age=4 }, - new() { Name="Whiskers", Age=1 } ]; + Pet[] pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; // Sort the Pet objects in the array by Pet.Age. IEnumerable query = pets.OrderBy(pet => pet.Age); @@ -1820,21 +1819,21 @@ static void SelectEx2() static class SelectMany1 { // - class PetOwner + class PetOwner(string name, List pets) { - public required string Name { get; set; } - public required List Pets { get; set; } + public string Name { get; set; } = name; + public List Pets { get; set; } = pets; } public static void SelectManyEx1() { - PetOwner[] petOwners = - [ new() { Name="Higa, Sidney", - Pets = ["Scruffy", "Sam"] }, - new() { Name="Ashkenazi, Ronen", - Pets = ["Walker", "Sugar"] }, - new() { Name="Price, Vernette", - Pets = ["Scratches", "Diesel"] } ]; + PetOwner[] petOwners = [ + new ("Higa, Sidney", + ["Scruffy", "Sam"] ), + new ("Ashkenazi, Ronen", + ["Walker", "Sugar"] ), + new ("Price, Vernette", + ["Scratches", "Diesel"] ) ]; // Query using SelectMany(). IEnumerable query1 = @@ -1897,23 +1896,23 @@ Using Select(): static class SelectMany2 { // - class PetOwner + class PetOwner(string name, List pets) { - public required string Name { get; set; } - public required List Pets { get; set; } + public string Name { get; set; } = name; + public List Pets { get; set; } = pets; } public static void SelectManyEx2() { - PetOwner[] petOwners = - [ new() { Name="Higa, Sidney", - Pets = ["Scruffy", "Sam"] }, - new() { Name="Ashkenazi, Ronen", - Pets = ["Walker", "Sugar"] }, - new() { Name="Price, Vernette", - Pets = ["Scratches", "Diesel"] }, - new() { Name="Hines, Patrick", - Pets = ["Dusty"] } ]; + PetOwner[] petOwners = [ + new ("Higa, Sidney", + ["Scruffy", "Sam"] ), + new ("Ashkenazi, Ronen", + ["Walker", "Sugar"] ), + new ("Price, Vernette", + ["Scratches", "Diesel"] ), + new ("Hines, Patrick", + ["Dusty"] ) ]; // For each PetOwner element in the source array, // project a sequence of strings where each string @@ -1946,46 +1945,41 @@ public static void SelectManyEx2() static class SelectMany3 { // - class PetOwner + class PetOwner(string name, List pets) { - public required string Name { get; set; } - public required List Pets { get; set; } + public string Name { get; set; } = name; + public List Pets { get; set; } = pets; } - class Pet + class Pet(string name, string breed) { - public required string Name { get; set; } - public required string Breed { get; set; } + public string Name { get; set; } = name; + public string Breed { get; set; } = breed; } public static void SelectManyEx3() { - PetOwner[] petOwners = - [ new() { Name="Higa", - Pets = [ - new() { Name="Scruffy", Breed="Poodle" }, - new() { Name="Sam", Breed="Hound" } ] }, - new() { Name="Ashkenazi", - Pets = [ - new() { Name="Walker", Breed="Collie" }, - new() { Name="Sugar", Breed="Poodle" } ] }, - new() { Name="Price", - Pets = [ - new() { Name="Scratches", Breed="Dachshund" }, - new() { Name="Diesel", Breed="Collie" } ] }, - new() { Name="Hines", - Pets = [ - new() { Name="Dusty", Breed="Collie" } ] } + PetOwner[] petOwners = [ + new ("Higa", [ + new ("Scruffy","Poodle" ), + new ("Sam","Hound" ) ] ), + new ("Ashkenazi", [ + new ("Walker","Collie" ), + new ("Sugar","Poodle" ) ] ), + new ("Price", [ + new ("Scratches","Dachshund" ), + new ("Diesel","Collie" ) ] ), + new ("Hines", [new ("Dusty","Collie" ) ] ) ]; // This query demonstrates how to obtain a sequence of // the names of all the pets whose breed is "Collie", while // keeping an association with the owner that owns the pet. var query = petOwners - // Create a sequence of ALL the Pet objects. Then - // project an anonymous type that consists of each - // Pet in the new sequence and the PetOwner object - // from the initial array that corresponds to that pet. + // Create a sequence of ALL the Pet objects. Then + // project an anonymous type that consists of each + // Pet in the new sequence and the PetOwner object + // from the initial array that corresponds to that pet. .SelectMany(owner => owner.Pets, (owner, pet) => new { owner, pet }) // Filter the sequence of anonymous types to only @@ -2021,16 +2015,16 @@ public static void SelectManyEx3() static class SequenceEqual1 { // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void SequenceEqualEx1() { - Pet pet1 = new() { Name = "Turbo", Age = 2 }; - Pet pet2 = new() { Name = "Peanut", Age = 8 }; + Pet pet1 = new("Turbo", 2); + Pet pet2 = new("Peanut", 8); // Create two lists of pets. List pets1 = [pet1, pet2]; @@ -2056,24 +2050,22 @@ The lists are equal. static class SequenceEqual2 { // - class Pet + class Pet(string name, int age) { - public required string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void SequenceEqualEx2() { - Pet pet1 = new() { Name = "Turbo", Age = 2 }; - Pet pet2 = new() { Name = "Peanut", Age = 8 }; + Pet pet1 = new("Turbo", 2); + Pet pet2 = new("Peanut", 8); // Create two lists of pets. List pets1 = [pet1, pet2]; - List pets2 = - [ - new Pet { Name = "Turbo", Age = 2 }, - new Pet { Name = "Peanut", Age = 8 } - ]; + List pets2 = [ + new Pet ("Turbo", 2 ), + new Pet ("Peanut", 8 ) ]; // Determine if the lists are equal. bool equal = pets1.SequenceEqual(pets2); @@ -2394,11 +2386,11 @@ class Package(string company, double weight) public static void SumEx3() { - List packages = - [ new Package ("Coho Vineyard", 25.2 ), - new Package ("Lucerne Publishing", 18.7 ), - new Package ("Wingtip Toys", 6.0 ), - new Package ("Adventure Works", 33.8 ) ]; + List packages = [ + new Package ("Coho Vineyard", 25.2 ), + new Package ("Lucerne Publishing", 18.7 ), + new Package ("Wingtip Toys", 6.0 ), + new Package ("Adventure Works", 33.8 ) ]; // Calculate the sum of all package weights. double totalWeight = packages @@ -2609,8 +2601,7 @@ 5 3 9 7 8 6 4 1 0 static void WhereEx1() { // - List fruits = - [ "apple", "passionfruit", "banana", "mango", + List fruits = [ "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry" ]; // Get all strings whose length is less than 6. From da86836a914cc63c14ccec4542f3f73bcbf1b9d9 Mon Sep 17 00:00:00 2001 From: DickBaker Date: Mon, 15 Jul 2024 18:26:46 +0100 Subject: [PATCH 5/8] COB715 --- snippets/csharp/System.Linq/.editorconfig | 22 +++++----- .../Enumerable/AggregateTSource/enumerable.cs | 10 ++--- .../Enumerable/Comparers/CustomComparer.cs | 44 +++++++++---------- .../Comparers/EncapsulatedComparer.cs | 30 ++++++------- .../ILookupTKey,TElement/Overview/ILookup.cs | 10 ++--- .../Queryable/AggregateTSource/queryable.cs | 36 +++++++-------- 6 files changed, 76 insertions(+), 76 deletions(-) diff --git a/snippets/csharp/System.Linq/.editorconfig b/snippets/csharp/System.Linq/.editorconfig index 7910af9eb54..624dffec1d2 100644 --- a/snippets/csharp/System.Linq/.editorconfig +++ b/snippets/csharp/System.Linq/.editorconfig @@ -118,17 +118,17 @@ csharp_style_prefer_primary_constructors = true:suggestion csharp_style_prefer_top_level_statements = true:silent # Expression-level preferences -csharp_prefer_simple_default_expression = true:suggestion -csharp_style_deconstructed_variable_declaration = true:suggestion -csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion -csharp_style_inlined_variable_declaration = true:suggestion -csharp_style_prefer_index_operator = true:suggestion -csharp_style_prefer_local_over_anonymous_function = true:suggestion -csharp_style_prefer_null_check_over_type_check = true:suggestion -csharp_style_prefer_range_operator = true:suggestion -csharp_style_prefer_tuple_swap = true:suggestion -csharp_style_prefer_utf8_string_literals = true:suggestion -csharp_style_throw_expression = true:suggestion +csharp_prefer_simple_default_expression = true +csharp_style_deconstructed_variable_declaration = true +csharp_style_implicit_object_creation_when_type_is_apparent = true +csharp_style_inlined_variable_declaration = true +csharp_style_prefer_index_operator = true +csharp_style_prefer_local_over_anonymous_function = true +csharp_style_prefer_null_check_over_type_check = true +csharp_style_prefer_range_operator = true +csharp_style_prefer_tuple_swap = true +csharp_style_prefer_utf8_string_literals = true +csharp_style_throw_expression = true csharp_style_unused_value_assignment_preference = discard_variable:silent csharp_style_unused_value_expression_statement_preference = discard_variable:silent diff --git a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs index fdf72d488de..d7298be32c9 100644 --- a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs +++ b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs @@ -158,7 +158,7 @@ public static void AnyEx1() { // List numbers = [1, 2]; - bool hasElements = numbers.Count != 0; + bool hasElements = numbers.Count > 0; Console.WriteLine("The list {0} empty.", hasElements ? "is not" : "is"); @@ -567,7 +567,7 @@ public static void DefaultIfEmptyEx1() new ("Boots", 4 ), new ("Whiskers", 1 ) ]; - foreach (var pet in pets.DefaultIfEmpty()) + foreach (Pet? pet in pets.DefaultIfEmpty()) { Console.WriteLine(pet?.Name); } @@ -601,7 +601,7 @@ static void DefaultIfEmptyEx1a() // } - static class DefaultIfEmtpy2 + static class DefaultIfEmpty2 { // class Pet(string name, int age) @@ -619,14 +619,14 @@ public static void DefaultIfEmptyEx2() new ("Boots", 4 ), new ("Whiskers", 1 ) ]; - foreach (Pet pet in pets1.DefaultIfEmpty(defaultPet)) + foreach (var pet in pets1.DefaultIfEmpty(defaultPet)) { Console.WriteLine("Name: {0}", pet.Name); } List pets2 = []; - foreach (Pet pet in pets2.DefaultIfEmpty(defaultPet)) + foreach (var pet in pets2.DefaultIfEmpty(defaultPet)) { Console.WriteLine("\nName: {0}", pet.Name); } diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs b/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs index f456b67b614..e9622811f68 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs @@ -49,12 +49,12 @@ static void Main() { // Product[] store1 = [ - new("apple",9 ), - new("orange",4 ) ]; + new ("apple",9 ), + new ("orange",4 ) ]; Product[] store2 = [ - new("apple",9 ), - new("lemon",12 ) ]; + new ("apple",9 ), + new ("lemon",12 ) ]; // Get the products from the first array // that have duplicates in the second array. @@ -75,12 +75,12 @@ apple 9 // Product[] store10 = [ - new("apple",9 ), - new("orange",4 ) ]; + new ("apple",9 ), + new ("orange",4 ) ]; Product[] store20 = [ - new("apple",9 ), - new("lemon",12 ) ]; + new ("apple",9 ), + new ("lemon",12 ) ]; //Get the products from the both arrays //excluding duplicates. @@ -104,10 +104,10 @@ lemon 12 // Product[] products = [ - new("apple",9 ), - new("orange",4 ), - new("apple",9 ), - new("lemon",12 ) ]; + new ("apple",9 ), + new ("orange",4 ), + new ("apple",9 ), + new ("lemon",12 ) ]; // Exclude duplicates. @@ -129,9 +129,9 @@ lemon 12 // Product[] fruits = [ - new("apple",9 ), - new("orange",4 ), - new("lemon",12 ) ]; + new ("apple",9 ), + new ("orange",4 ), + new ("lemon",12 ) ]; Product apple = new("apple", 9); Product kiwi = new("kiwi", 8); @@ -155,9 +155,9 @@ lemon 12 // Product[] fruits1 = [ - new("apple",9 ), - new("orange",4 ), - new("lemon",12 ) ]; + new ("apple",9 ), + new ("orange",4 ), + new ("lemon",12 ) ]; Product[] fruits2 = [new("apple", 9)]; @@ -184,12 +184,12 @@ lemon 12 // Product[] storeA = [ - new("apple",9 ), - new("orange",4 ) ]; + new ("apple",9 ), + new ("orange",4 ) ]; Product[] storeB = [ - new("apple",9 ), - new("orange",4 ) ]; + new ("apple",9 ), + new ("orange",4 ) ]; var equalAB = storeA.SequenceEqual(storeB, new ProductComparer()); diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs b/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs index 5bb3ef368c4..285acab8db3 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs @@ -50,12 +50,12 @@ static void Main() // ProductComparer, which implements IEqualityComparer (not IEquatable). // ProductA[] store1 = [ - new("apple", 9 ), - new("orange", 4 ) ]; + new ("apple", 9 ), + new ("orange", 4 ) ]; ProductA[] store2 = [ - new("apple", 9 ), - new("lemon", 12 ) ]; + new ("apple", 9 ), + new ("lemon", 12 ) ]; // // @@ -99,10 +99,10 @@ lemon 12 // MyProduct[] products = [ - new("apple", 9 ), - new("orange", 4 ), - new("apple", 9 ), - new("lemon", 12 ) ]; + new ("apple", 9 ), + new ("orange", 4 ), + new ("apple", 9 ), + new ("lemon", 12 ) ]; // Exclude duplicates. @@ -124,9 +124,9 @@ lemon 12 // ProductA[] fruits1 = [ - new("apple", 9 ), - new("orange", 4 ), - new("lemon", 12 ) ]; + new ("apple", 9 ), + new ("orange", 4 ), + new ("lemon", 12 ) ]; ProductA[] fruits2 = [new("apple", 9)]; @@ -152,12 +152,12 @@ lemon 12 // ProductA[] storeA = [ - new("apple", 9 ), - new("orange", 4 ) ]; + new ("apple", 9 ), + new ("orange", 4 ) ]; ProductA[] storeB = [ - new("apple", 9 ), - new("orange", 4 ) ]; + new ("apple", 9 ), + new ("orange", 4 ) ]; var equalAB = storeA.SequenceEqual(storeB); diff --git a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs index 7cd60d30352..d0e8beab18d 100644 --- a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs +++ b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs @@ -20,11 +20,11 @@ public static void ILookupExample() { // Create a list of Packages to put into an ILookup data structure. List packages = [ - new Package ("Coho Vineyard", 25.2, 89453312L ), - new Package ("Lucerne Publishing", 18.7, 89112755L ), - new Package ("Wingtip Toys", 6.0, 299456122L ), - new Package ("Contoso Pharmaceuticals", 9.3, 670053128L ), - new Package ("Wide World Importers", 33.8, 4665518773L ) ]; + new ("Coho Vineyard", 25.2, 89453312L ), + new ("Lucerne Publishing", 18.7, 89112755L ), + new ("Wingtip Toys", 6.0, 299456122L ), + new ("Contoso Pharmaceuticals", 9.3, 670053128L ), + new ("Wide World Importers", 33.8, 4665518773L ) ]; // Create a Lookup to organize the packages. Use the first character of Company as the key value. // Select Company appended to TrackingNumber for each element value in the ILookup object. diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs b/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs index ee388ef44c4..d5ee5f634dd 100644 --- a/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs +++ b/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs @@ -138,11 +138,11 @@ public static void AllEx2() new ("Barley",10 ), new ("Boots",14 ), new ("Whiskers",6 ) ]), - new("Fakhouri", [ new("Snowball", 1) ]), - new("Antebi", [ new("Belle", 8) ]), + new ("Fakhouri", [ new ("Snowball", 1) ]), + new ("Antebi", [ new ("Belle", 8) ]), new ("Philips", [ - new("Sweetie", 2), - new("Rover", 13) ] ) ]; + new ("Sweetie", 2), + new ("Rover", 13) ] ) ]; // Determine which people have pets that are all older than 5. IEnumerable names = from person in people @@ -173,7 +173,7 @@ public static void AnyEx1() List numbers = [1, 2]; // Determine if the list contains any elements. - bool hasElements = numbers.Any(); // [CA1860] better to use "numbers.Count != 0;" ! + bool hasElements = numbers.Any(); // [CA1860] better to use "numbers.Count > 0;" ! Console.WriteLine("The list {0} empty.", hasElements ? "is not" : "is"); @@ -204,11 +204,11 @@ public static void AnyEx2() new ("Barley",10 ), new ("Boots",14 ), new ("Whiskers",6 ) ]), - new("Fakhouri", [ new("Snowball", 1) ]), - new("Antebi",[]), - new("Philips", [ - new("Sweetie", 2), - new("Rover", 13) ] ) + new ("Fakhouri", [ new ("Snowball", 1) ]), + new ("Antebi",[]), + new ("Philips", [ + new ("Sweetie", 2), + new ("Rover", 13) ] ) ]; // Determine which people have a non-empty Pet array. @@ -598,7 +598,7 @@ public static void DefaultIfEmptyEx1() new ("Boots",4 ), new ("Whiskers",1 ) ]; - // Call DefaultIfEmtpy() on the collection that Select() + // Call DefaultIfEmpty() on the collection that Select() // returns, so that if the initial list is empty, there // will always be at least one item in the returned array. string[] names = [.. pets @@ -1246,7 +1246,7 @@ public static void JoinEx1() Person terry = new("Adams, Terry"); Person charlotte = new("Weiss, Charlotte"); - Pet barley = new Pet("Barley", terry); + Pet barley = new("Barley", terry); Pet boots = new("Boots", terry); Pet whiskers = new("Whiskers", charlotte); Pet daisy = new("Daisy", magnus); @@ -2064,8 +2064,8 @@ public static void SequenceEqualEx2() // Create two lists of pets. List pets1 = [pet1, pet2]; List pets2 = [ - new Pet ("Turbo", 2 ), - new Pet ("Peanut", 8 ) ]; + new ("Turbo", 2 ), + new ("Peanut", 8 ) ]; // Determine if the lists are equal. bool equal = pets1.SequenceEqual(pets2); @@ -2387,10 +2387,10 @@ class Package(string company, double weight) public static void SumEx3() { List packages = [ - new Package ("Coho Vineyard", 25.2 ), - new Package ("Lucerne Publishing", 18.7 ), - new Package ("Wingtip Toys", 6.0 ), - new Package ("Adventure Works", 33.8 ) ]; + new ("Coho Vineyard", 25.2 ), + new ("Lucerne Publishing", 18.7 ), + new ("Wingtip Toys", 6.0 ), + new ("Adventure Works", 33.8 ) ]; // Calculate the sum of all package weights. double totalWeight = packages From de5953a221cc0efc66bc60f2311e8254511e86bc Mon Sep 17 00:00:00 2001 From: DickBaker Date: Mon, 15 Jul 2024 18:57:23 +0100 Subject: [PATCH 6/8] upload for PR (after removing Roslynator) --- .../Enumerable/AggregateTSource/Enumerable.csproj | 7 ------- .../System.Linq/Enumerable/Comparers/Comparers.csproj | 7 ------- .../IGroupingTKey,TElement/Overview/IGrouping.csproj | 7 ------- .../ILookupTKey,TElement/Overview/ILookup.csproj | 7 ------- .../Overview/IOrderedEnumerable.csproj | 7 ------- .../Queryable/AggregateTSource/AggregateTSource.csproj | 7 ------- 6 files changed, 42 deletions(-) diff --git a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj index c5d80d0822a..f432dbe7e6f 100644 --- a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj +++ b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj @@ -6,11 +6,4 @@ enable - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj b/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj index 0f763c6eaab..dd998a3c7af 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj @@ -8,11 +8,4 @@ latest - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - diff --git a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj index e1cea776ebd..b2438766608 100644 --- a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj +++ b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj @@ -6,11 +6,4 @@ enable - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj index e1cea776ebd..b2438766608 100644 --- a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj +++ b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj @@ -6,11 +6,4 @@ enable - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj index e1cea776ebd..b2438766608 100644 --- a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj +++ b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj @@ -6,11 +6,4 @@ enable - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj b/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj index a1e576757e6..030872b60a5 100644 --- a/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj +++ b/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj @@ -5,12 +5,5 @@ net8.0 enable - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - From 3eb845248a38fb6b5e970219959dde8981788b25 Mon Sep 17 00:00:00 2001 From: DickBaker Date: Wed, 10 Jul 2024 09:17:00 +0100 Subject: [PATCH 7/8] squash my commits for clean PR --- snippets/csharp/System.Linq/.editorconfig | 269 ++++ .../AggregateTSource/Enumerable.csproj | 3 +- .../Enumerable/AggregateTSource/enumerable.cs | 1080 ++++++++--------- .../Enumerable/Comparers/Comparers.csproj | 8 +- .../Enumerable/Comparers/CustomComparer.cs | 123 +- .../Comparers/EncapsulatedComparer.cs | 106 +- .../Overview/IGrouping.csproj | 9 + .../Overview/Project.csproj | 8 - .../Overview/igrouping.cs | 25 +- .../ILookupTKey,TElement/Overview/ILookup.cs | 29 +- .../Overview/ILookup.csproj | 9 + .../Overview/Project.csproj | 8 - .../Overview/IOrderedEnumerable.cs | 17 +- .../Overview/IOrderedEnumerable.csproj | 9 + .../Overview/Project.csproj | 8 - snippets/csharp/System.Linq/Linq - Copy.txt | 61 + .../Overview/Project.csproj | 8 - .../AggregateTSource/AggregateTSource.csproj | 9 + .../Queryable/AggregateTSource/Project.csproj | 8 - .../Queryable/AggregateTSource/queryable.cs | 1016 ++++++++-------- snippets/csharp/System.Linq/README.txt | 9 + 21 files changed, 1592 insertions(+), 1230 deletions(-) create mode 100644 snippets/csharp/System.Linq/.editorconfig create mode 100644 snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj delete mode 100644 snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/Project.csproj create mode 100644 snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj delete mode 100644 snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/Project.csproj create mode 100644 snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj delete mode 100644 snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/Project.csproj create mode 100644 snippets/csharp/System.Linq/Linq - Copy.txt delete mode 100644 snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Project.csproj create mode 100644 snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj delete mode 100644 snippets/csharp/System.Linq/Queryable/AggregateTSource/Project.csproj create mode 100644 snippets/csharp/System.Linq/README.txt diff --git a/snippets/csharp/System.Linq/.editorconfig b/snippets/csharp/System.Linq/.editorconfig new file mode 100644 index 00000000000..624dffec1d2 --- /dev/null +++ b/snippets/csharp/System.Linq/.editorconfig @@ -0,0 +1,269 @@ +# Remove the line below if you want to inherit .editorconfig settings from higher directories +root = true + +# C# files +[*.cs] + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_size = 4 +indent_style = space +tab_width = 4 + +# New line preferences +end_of_line = crlf +insert_final_newline = false + +#### .NET Coding Conventions #### + +# Organize usings +dotnet_separate_import_directive_groups = false +dotnet_sort_system_directives_first = true +file_header_template = unset + +# this. and Me. preferences +dotnet_style_qualification_for_event = false +dotnet_style_qualification_for_field = false +dotnet_style_qualification_for_method = false +dotnet_style_qualification_for_property = false + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true +dotnet_style_predefined_type_for_member_access = true + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary +dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary +dotnet_style_parentheses_in_other_operators = never_if_unnecessary +dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members + +# Expression-level preferences +dotnet_style_coalesce_expression = true +dotnet_style_collection_initializer = true +dotnet_style_explicit_tuple_names = true +dotnet_style_namespace_match_folder = true +dotnet_style_null_propagation = true +dotnet_style_object_initializer = true +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_prefer_auto_properties = true:warning +dotnet_style_prefer_collection_expression = when_types_loosely_match +dotnet_style_prefer_compound_assignment = true +dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = true:suggestion +dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed +dotnet_style_prefer_inferred_anonymous_type_member_names = true +dotnet_style_prefer_inferred_tuple_names = true +dotnet_style_prefer_is_null_check_over_reference_equality_method = true +dotnet_style_prefer_simplified_boolean_expressions = true +dotnet_style_prefer_simplified_interpolation = true + +# Field preferences +dotnet_style_readonly_field = true + +# Parameter preferences +dotnet_code_quality_unused_parameters = all + +# Suppression preferences +dotnet_remove_unnecessary_suppression_exclusions = none + +# New line preferences +dotnet_style_allow_multiple_blank_lines_experimental = false +dotnet_style_allow_statement_immediately_after_block_experimental = true + +#### C# Coding Conventions #### + +# var preferences +csharp_style_var_elsewhere = false:silent +csharp_style_var_for_built_in_types = true:silent +csharp_style_var_when_type_is_apparent = true:silent + +# Expression-bodied members +csharp_style_expression_bodied_accessors = true:suggestion +csharp_style_expression_bodied_constructors = true:suggestion +csharp_style_expression_bodied_indexers = true:suggestion +csharp_style_expression_bodied_lambdas = true:suggestion +csharp_style_expression_bodied_local_functions = true:suggestion +csharp_style_expression_bodied_methods = true:suggestion +csharp_style_expression_bodied_operators = true:suggestion +csharp_style_expression_bodied_properties = true:suggestion + +# Pattern matching preferences +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_prefer_extended_property_pattern = true:suggestion +csharp_style_prefer_not_pattern = true:suggestion +csharp_style_prefer_pattern_matching = true:suggestion +csharp_style_prefer_switch_expression = true:suggestion + +# Null-checking preferences +csharp_style_conditional_delegate_call = true:suggestion + +# Modifier preferences +csharp_prefer_static_anonymous_function = true:suggestion +csharp_prefer_static_local_function = true:suggestion +csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async +csharp_style_prefer_readonly_struct = true:suggestion +csharp_style_prefer_readonly_struct_member = true:suggestion + +# Code-block preferences +csharp_prefer_braces = true:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_style_namespace_declarations = file_scoped:silent +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_primary_constructors = true:suggestion +csharp_style_prefer_top_level_statements = true:silent + +# Expression-level preferences +csharp_prefer_simple_default_expression = true +csharp_style_deconstructed_variable_declaration = true +csharp_style_implicit_object_creation_when_type_is_apparent = true +csharp_style_inlined_variable_declaration = true +csharp_style_prefer_index_operator = true +csharp_style_prefer_local_over_anonymous_function = true +csharp_style_prefer_null_check_over_type_check = true +csharp_style_prefer_range_operator = true +csharp_style_prefer_tuple_swap = true +csharp_style_prefer_utf8_string_literals = true +csharp_style_throw_expression = true +csharp_style_unused_value_assignment_preference = discard_variable:silent +csharp_style_unused_value_expression_statement_preference = discard_variable:silent + +# 'using' directive preferences +csharp_using_directive_placement = outside_namespace:suggestion + +# New line preferences +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false:silent +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false:silent +csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = true +csharp_new_line_before_else = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = all +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Wrapping preferences +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +[*.{cs,vb}] +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = crlf +dotnet_style_namespace_match_folder = true:suggestion +dotnet_style_predefined_type_for_member_access = true:silent +dotnet_style_require_accessibility_modifiers = omit_if_default:silent +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_property = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_event = false:silent +dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_other_operators = always_for_clarity:silent +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:warning +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion +dotnet_style_readonly_field = true:suggestion +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_allow_multiple_blank_lines_experimental = false:silent +dotnet_style_allow_statement_immediately_after_block_experimental = true:silent +dotnet_code_quality_unused_parameters = all:suggestion \ No newline at end of file diff --git a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj index a269962b552..f432dbe7e6f 100644 --- a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj +++ b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/Enumerable.csproj @@ -1,8 +1,9 @@ - + Exe net8.0 + enable diff --git a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs index 5b7949c4f0c..d7298be32c9 100644 --- a/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs +++ b/snippets/csharp/System.Linq/Enumerable/AggregateTSource/enumerable.cs @@ -4,19 +4,16 @@ namespace SequenceExamples { - class Program + static class Program { // This part is just for testing the examples - static void Main(string[] args) - { - OfTypeEx1(); - } + static void Main() => OfTypeEx1(); #region Aggregate static void AggregateEx1() { // - string sentence = "the quick brown fox jumps over the lazy dog"; + const string sentence = "the quick brown fox jumps over the lazy dog"; // Split the string into individual words. string[] words = sentence.Split(' '); @@ -36,7 +33,7 @@ static void AggregateEx1() static void AggregateEx2() { // - int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 }; + int[] ints = [4, 8, 8, 3, 9, 0, 7, 8, 2]; // Count the even numbers in the array, using a seed value of 0. int numEven = ints.Aggregate(0, (total, next) => @@ -52,7 +49,7 @@ static void AggregateEx2() static void AggregateEx3() { // - string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" }; + string[] fruits = ["apple", "mango", "orange", "passionfruit", "grape"]; // Determine whether any string in the array is longer than "banana". string longestName = @@ -77,23 +74,23 @@ static void AggregateEx3() static class All { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void AllEx() { // Create an array of Pets. - Pet[] pets = { new Pet { Name="Barley", Age=10 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=6 } }; + Pet[] pets = [ + new ("Barley", 10 ), + new ("Boots", 4 ), + new ("Whiskers", 6 ) ]; // Determine whether all pet names // in the array start with 'B'. - bool allStartWithB = pets.All(pet => - pet.Name.StartsWith("B")); + bool allStartWithB = pets.All(pet => pet.Name.StartsWith('B')); Console.WriteLine( "{0} pet names start with 'B'.", @@ -109,32 +106,29 @@ public static void AllEx() static class All2 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } - class Person + class Person(string lastName, Pet[] pets) { - public string LastName { get; set; } - public Pet[] Pets { get; set; } + public string LastName { get; set; } = lastName; + public Pet[] Pets { get; set; } = pets; } public static void AllEx2() { - List people = new List - { new Person { LastName = "Haas", - Pets = new Pet[] { new Pet { Name="Barley", Age=10 }, - new Pet { Name="Boots", Age=14 }, - new Pet { Name="Whiskers", Age=6 }}}, - new Person { LastName = "Fakhouri", - Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}}, - new Person { LastName = "Antebi", - Pets = new Pet[] { new Pet { Name = "Belle", Age = 8} }}, - new Person { LastName = "Philips", - Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2}, - new Pet { Name = "Rover", Age = 13}} } - }; + List people = [ + new ("Haas", [ + new ("Barley", 10 ), + new ("Boots", 14 ), + new ("Whiskers", 6 ) ]), + new ("Fakhouri", [ new ("Snowball", 1) ]), + new ("Antebi", [ new ("Belle", 8) ]), + new ("Philips", [ + new ("Sweetie", 2), + new ("Rover", 13) ] ) ]; // Determine which people have pets that are all older than 5. IEnumerable names = from person in people @@ -163,8 +157,8 @@ static class Any1 public static void AnyEx1() { // - List numbers = new List { 1, 2 }; - bool hasElements = numbers.Any(); + List numbers = [1, 2]; + bool hasElements = numbers.Count > 0; Console.WriteLine("The list {0} empty.", hasElements ? "is not" : "is"); @@ -176,36 +170,34 @@ public static void AnyEx1() } // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } - class Person + class Person(string lastName, Pet[] pets) { - public string LastName { get; set; } - public Pet[] Pets { get; set; } + public string LastName { get; set; } = lastName; + public Pet[] Pets { get; set; } = pets; } public static void AnyEx2() { - List people = new List - { new Person { LastName = "Haas", - Pets = new Pet[] { new Pet { Name="Barley", Age=10 }, - new Pet { Name="Boots", Age=14 }, - new Pet { Name="Whiskers", Age=6 }}}, - new Person { LastName = "Fakhouri", - Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}}, - new Person { LastName = "Antebi", - Pets = new Pet[] { }}, - new Person { LastName = "Philips", - Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2}, - new Pet { Name = "Rover", Age = 13}} } - }; + List people = [ + new ("Haas", [ + new ("Barley", 10 ), + new ("Boots", 14 ), + new ("Whiskers", 6 ) ]), + new ("Fakhouri", [ new ("Snowball", 1) ]), + new ("Antebi", []), + new ("Philips", [ + new ("Sweetie", 2), + new ("Rover", 13) ] ) + ]; // Determine which people have a non-empty Pet array. IEnumerable names = from person in people - where person.Pets.Any() + where person.Pets.Length != 0 select person.LastName; foreach (string name in names) @@ -226,24 +218,24 @@ where person.Pets.Any() static class Any2 { // - class Pet + class Pet(string name, int age, bool vaccinated) { - public string Name { get; set; } - public int Age { get; set; } - public bool Vaccinated { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; + public bool Vaccinated { get; set; } = vaccinated; } public static void AnyEx3() { // Create an array of Pets. - Pet[] pets = - { new Pet { Name="Barley", Age=8, Vaccinated=true }, - new Pet { Name="Boots", Age=4, Vaccinated=false }, - new Pet { Name="Whiskers", Age=1, Vaccinated=false } }; + Pet[] pets = [ + new ("Barley", 8, true ), + new ("Boots", 4, false ), + new ("Whiskers", 1, false ) ]; // Determine whether any pets over age 1 are also unvaccinated. bool unvaccinated = - pets.Any(p => p.Age > 1 && p.Vaccinated == false); + pets.Any(p => p.Age > 1 && !p.Vaccinated); Console.WriteLine( "There {0} unvaccinated animals over age one.", @@ -275,13 +267,14 @@ static void AsEnumerableEx1() { // Create a new Clump object. Clump fruitClump = - new Clump { "apple", "passionfruit", "banana", + new() + { "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry" }; // First call to Where(): // Call Clump's Where() method with a predicate. IEnumerable query1 = - fruitClump.Where(fruit => fruit.Contains("o")); + fruitClump.Where(fruit => fruit.Contains('o')); Console.WriteLine("query1 has been created.\n"); @@ -289,7 +282,7 @@ static void AsEnumerableEx1() // First call AsEnumerable() to hide Clump's Where() method and thereby // force System.Linq.Enumerable's Where() method to be called. IEnumerable query2 = - fruitClump.AsEnumerable().Where(fruit => fruit.Contains("o")); + fruitClump.AsEnumerable().Where(fruit => fruit.Contains('o')); // Display the output. Console.WriteLine("query2 has been created."); @@ -308,7 +301,7 @@ static void AsEnumerableEx1() static void AverageEx1() { // - List grades = new List { 78, 92, 100, 37, 81 }; + List grades = [78, 92, 100, 37, 81]; double average = grades.Average(); @@ -323,7 +316,7 @@ static void AverageEx1() static void AverageEx2() { // - long?[] longs = { null, 10007L, 37L, 399846234235L }; + long?[] longs = [null, 10007L, 37L, 399846234235L]; double? average = longs.Average(); @@ -338,9 +331,9 @@ static void AverageEx2() static void AverageEx3() { // - string[] numbers = { "10007", "37", "299846234235" }; + string[] numbers = ["10007", "37", "299846234235"]; - double average = numbers.Average(num => long.Parse(num)); + double average = numbers.Average(long.Parse); Console.WriteLine("The average is {0}.", average); @@ -353,7 +346,7 @@ static void AverageEx3() static void AverageEx4() { // - string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; + string[] fruits = ["apple", "banana", "mango", "orange", "passionfruit", "grape"]; double average = fruits.Average(s => s.Length); @@ -370,17 +363,14 @@ static void AverageEx4() static void CastEx1() { // - System.Collections.ArrayList fruits = new System.Collections.ArrayList(); - fruits.Add("mango"); - fruits.Add("apple"); - fruits.Add("lemon"); + System.Collections.ArrayList fruits = ["mango", "apple", "lemon"]; - IEnumerable query = - fruits.Cast().OrderBy(fruit => fruit).Select(fruit => fruit); + IEnumerable query = fruits.Cast() + .OrderBy(fruit => fruit) + .Select(fruit => fruit); - // The following code, without the cast, doesn't compile. - //IEnumerable query1 = - // fruits.OrderBy(fruit => fruit).Select(fruit => fruit); + //The following code, without the cast, doesn't compile (no System.Linq.Enumerable.OrderBy extension method for ArrayList) + //var query1 = fruits.OrderBy(fruit => fruit).Select(fruit => fruit); foreach (string fruit in query) { @@ -400,25 +390,27 @@ static void CastEx1() static class Concat { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } static Pet[] GetCats() { - Pet[] cats = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] cats = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; return cats; } static Pet[] GetDogs() { - Pet[] dogs = { new Pet { Name="Bounder", Age=3 }, - new Pet { Name="Snoopy", Age=14 }, - new Pet { Name="Fido", Age=9 } }; + Pet[] dogs = [ + new ("Bounder", 3 ), + new ("Snoopy", 14 ), + new ("Fido", 9 ) ]; return dogs; } @@ -427,8 +419,9 @@ public static void ConcatEx1() Pet[] cats = GetCats(); Pet[] dogs = GetDogs(); - IEnumerable query = - cats.Select(cat => cat.Name).Concat(dogs.Select(dog => dog.Name)); + IEnumerable query = cats + .Select(cat => cat.Name) + .Concat(dogs.Select(dog => dog.Name)); foreach (string name in query) { @@ -452,8 +445,9 @@ public static void ConcatEx2() Pet[] cats = GetCats(); Pet[] dogs = GetDogs(); - IEnumerable query = - new[] { cats.Select(cat => cat.Name), dogs.Select(dog => dog.Name) } + IEnumerable query = new[] + { cats.Select(cat => cat.Name), + dogs.Select(dog => dog.Name) } .SelectMany(name => name); foreach (string name in query) @@ -478,9 +472,9 @@ public static void ConcatEx2() static void ContainsEx1() { // - string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; + string[] fruits = ["apple", "banana", "mango", "orange", "passionfruit", "grape"]; - string fruit = "mango"; + const string fruit = "mango"; bool hasMango = fruits.Contains(fruit); @@ -500,11 +494,11 @@ static void ContainsEx1() static void CountEx1() { // - string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; + string[] fruits = ["apple", "banana", "mango", "orange", "passionfruit", "grape"]; try { - int numberOfFruits = fruits.Count(); + int numberOfFruits = fruits.Length; Console.WriteLine( "There are {0} fruits in the collection.", numberOfFruits); @@ -524,21 +518,22 @@ static void CountEx1() static class Count { // - class Pet + class Pet(string name, bool vaccinated) { - public string Name { get; set; } - public bool Vaccinated { get; set; } + public string Name { get; set; } = name; + public bool Vaccinated { get; set; } = vaccinated; } public static void CountEx2() { - Pet[] pets = { new Pet { Name="Barley", Vaccinated=true }, - new Pet { Name="Boots", Vaccinated=false }, - new Pet { Name="Whiskers", Vaccinated=false } }; + Pet[] pets = [ + new ("Barley", true ), + new ("Boots", false ), + new ("Whiskers", false ) ]; try { - int numberUnvaccinated = pets.Count(p => p.Vaccinated == false); + int numberUnvaccinated = pets.Count(p => !p.Vaccinated); Console.WriteLine("There are {0} unvaccinated animals.", numberUnvaccinated); } catch (OverflowException) @@ -559,22 +554,22 @@ public static void CountEx2() static class DefaultIfEmpty1 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void DefaultIfEmptyEx1() { - List pets = - new List{ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + List pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; - foreach (Pet pet in pets.DefaultIfEmpty()) + foreach (Pet? pet in pets.DefaultIfEmpty()) { - Console.WriteLine(pet.Name); + Console.WriteLine(pet?.Name); } } @@ -591,7 +586,7 @@ public static void DefaultIfEmptyEx1() static void DefaultIfEmptyEx1a() { // - List numbers = new List(); + List numbers = []; foreach (int number in numbers.DefaultIfEmpty()) { @@ -606,32 +601,32 @@ static void DefaultIfEmptyEx1a() // } - static class DefaultIfEmtpy2 + static class DefaultIfEmpty2 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void DefaultIfEmptyEx2() { - Pet defaultPet = new Pet { Name = "Default Pet", Age = 0 }; + Pet defaultPet = new("Default Pet", 0); - List pets1 = - new List{ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + List pets1 = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; - foreach (Pet pet in pets1.DefaultIfEmpty(defaultPet)) + foreach (var pet in pets1.DefaultIfEmpty(defaultPet)) { Console.WriteLine("Name: {0}", pet.Name); } - List pets2 = new List(); + List pets2 = []; - foreach (Pet pet in pets2.DefaultIfEmpty(defaultPet)) + foreach (var pet in pets2.DefaultIfEmpty(defaultPet)) { Console.WriteLine("\nName: {0}", pet.Name); } @@ -654,7 +649,7 @@ public static void DefaultIfEmptyEx2() static void DistinctEx1() { // - List ages = new List { 21, 46, 46, 55, 17, 21, 55, 55 }; + List ages = [21, 46, 46, 55, 17, 21, 55, 55]; IEnumerable distinctAges = ages.Distinct(); @@ -682,13 +677,11 @@ static void DistinctEx1() static void ElementAtEx1() { // - string[] names = - { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - - "Hedlund, Magnus", "Ito, Shu" }; - Random random = new Random(DateTime.Now.Millisecond); + string[] names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", + "Hedlund, Magnus", "Ito, Shu" ]; + Random random = new(DateTime.Now.Millisecond); - string name = names.ElementAt(random.Next(0, names.Length)); + string name = names[random.Next(0, names.Length)]; Console.WriteLine("The name chosen at random is '{0}'.", name); @@ -705,18 +698,18 @@ static void ElementAtEx1() static void ElementAtOrDefaultEx1() { // - string[] names = - { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; + string[] names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", + "Hedlund, Magnus", "Ito, Shu" ]; - int index = 20; + const int index = 20; - string name = names.ElementAtOrDefault(index); + var name = names.ElementAtOrDefault(index); + //var name = names[index]; Console.WriteLine( "The name chosen at index {0} is '{1}'.", index, - String.IsNullOrEmpty(name) ? "" : name); + name ?? ""); /* This code produces the following output: @@ -731,27 +724,28 @@ The name chosen at index 20 is ''. static void EmptyEx1() { // - IEnumerable empty = Enumerable.Empty(); + IEnumerable empty = []; // } static void EmptyEx2() { // - string[] names1 = { "Hartono, Tommy" }; - string[] names2 = { "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; - string[] names3 = { "Solanki, Ajay", "Hoeing, Helge", + string[] names1 = ["Hartono, Tommy"]; + string[] names2 = [ "Adams, Terry", "Andersen, Henriette Thaulow", + "Hedlund, Magnus", "Ito, Shu" ]; + string[] names3 = [ "Solanki, Ajay", "Hoeing, Helge", "Andersen, Henriette Thaulow", - "Potra, Cristina", "Iallo, Lucio" }; + "Potra, Cristina", "Iallo, Lucio" ]; List namesList = - new List { names1, names2, names3 }; + [names1, names2, names3]; // Only include arrays that have four or more elements IEnumerable allNames = namesList.Aggregate(Enumerable.Empty(), - (current, next) => next.Length > 3 ? current.Union(next) : current); + (current, next) => + next.Length > 3 ? current.Union(next) : current); foreach (string name in allNames) { @@ -778,13 +772,15 @@ static void EmptyEx2() static void ExceptEx1() { // - double[] numbers1 = { 2.0, 2.0, 2.1, 2.2, 2.3, 2.3, 2.4, 2.5 }; - double[] numbers2 = { 2.2 }; + double[] numbers1 = [2.0, 2.0, 2.1, 2.2, 2.3, 2.3, 2.4, 2.5]; + double[] numbers2 = [2.2]; IEnumerable onlyInFirstSet = numbers1.Except(numbers2); foreach (double number in onlyInFirstSet) + { Console.WriteLine(number); + } /* This code produces the following output: @@ -803,10 +799,10 @@ static void ExceptEx1() static void FirstEx1() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 435, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 435, 67, 12, 19 ]; - int first = numbers.First(); + int first = numbers[0]; Console.WriteLine(first); @@ -821,8 +817,8 @@ static void FirstEx1() static void FirstEx2() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 435, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 435, 67, 12, 19 ]; int first = numbers.First(number => number > 80); @@ -841,7 +837,7 @@ static void FirstEx2() static void FirstOrDefaultEx1() { // - int[] numbers = { }; + int[] numbers = []; int first = numbers.FirstOrDefault(); Console.WriteLine(first); @@ -856,19 +852,18 @@ static void FirstOrDefaultEx1() static void FirstOrDefaultEx2() { // - string[] names = { "Hartono, Tommy", "Adams, Terry", + string[] names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; + "Hedlund, Magnus", "Ito, Shu" ]; - string firstLongName = names.FirstOrDefault(name => name.Length > 20); + var firstLongName = names.FirstOrDefault(name => name.Length > 20); Console.WriteLine("The first long name is '{0}'.", firstLongName); - string firstVeryLongName = names.FirstOrDefault(name => name.Length > 30); + var firstVeryLongName = names.FirstOrDefault(name => name.Length > 30); - Console.WriteLine( - "There is {0} name longer than 30 characters.", - string.IsNullOrEmpty(firstVeryLongName) ? "not a" : "a"); + Console.WriteLine("There is {0} name longer than 30 characters.", + firstVeryLongName is null ? "not a" : "a"); /* This code produces the following output: @@ -882,7 +877,7 @@ There is not a name longer than 30 characters. static void FirstOrDefaultEx3() { // - List months = new List { }; + List months = []; // Setting the default value to 1 after the query. int firstMonth1 = months.FirstOrDefault(); @@ -910,21 +905,21 @@ The value of the firstMonth2 variable is 1 static class GroupBy { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } // Uses method-based query syntax. public static void GroupByEx1() { // Create a list of pets. - List pets = - new List{ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 }, - new Pet { Name="Daisy", Age=4 } }; + List pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ), + new ("Daisy", 4 ) ]; // Group the pets using Age as the key value // and selecting only the pet's Name for each value. @@ -939,7 +934,9 @@ public static void GroupByEx1() // Iterate over each value in the // IGrouping and print the value. foreach (string name in petGroup) + { Console.WriteLine(" {0}", name); + } } } @@ -960,14 +957,14 @@ public static void GroupByEx1() public static void GroupByEx2() { // Create a list of pets. - List pets = - new List{ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 }, - new Pet { Name="Daisy", Age=4 } }; + List pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ), + new ("Daisy", 4 ) ]; // Group the pets using Age as the key value - // and selecting only the pet's Name for each value. + // and selecting only the pet's name for each value. // IEnumerable> query = from pet in pets @@ -982,7 +979,9 @@ from pet in pets // Iterate over each value in the IGrouping // and print the value. foreach (string name in petGroup) + { Console.WriteLine(" {0}", name); + } } } } @@ -990,30 +989,30 @@ from pet in pets static class GroupBy3 { // - class Pet + class Pet(string name, float age) { - public string Name { get; set; } - public double Age { get; set; } + public string Name { get; set; } = name; + public float Age { get; set; } = age; } public static void GroupByEx3() { // Create a list of pets. - List petsList = - new List{ new Pet { Name="Barley", Age=8.3 }, - new Pet { Name="Boots", Age=4.9 }, - new Pet { Name="Whiskers", Age=1.5 }, - new Pet { Name="Daisy", Age=4.3 } }; + List petsList = [ + new ("Barley", 8.3f ), + new ("Boots", 4.9f ), + new ("Whiskers", 1.5f ), + new ("Daisy", 4.3f ) ]; // Group Pet objects by the Math.Floor of their age. // Then project an anonymous type from each group // that consists of the key, the count of the group's // elements, and the minimum and maximum age in the group. var query = petsList.GroupBy( - pet => Math.Floor(pet.Age), - (age, pets) => new + pet => (int)Math.Floor(pet.Age), + (baseAge, pets) => new { - Key = age, + Key = baseAge, Count = pets.Count(), Min = pets.Min(pet => pet.Age), Max = pets.Max(pet => pet.Age) @@ -1053,27 +1052,27 @@ public static void GroupByEx3() static class GroupBy4 { // - class Pet + class Pet(string name, float age) { - public string Name { get; set; } - public double Age { get; set; } + public string Name { get; set; } = name; + public float Age { get; set; } = age; } public static void GroupByEx4() { // Create a list of pets. - List petsList = - new List{ new Pet { Name="Barley", Age=8.3 }, - new Pet { Name="Boots", Age=4.9 }, - new Pet { Name="Whiskers", Age=1.5 }, - new Pet { Name="Daisy", Age=4.3 } }; + List petsList = [ + new ("Barley", 8.3f ), + new ("Boots", 4.9f ), + new ("Whiskers", 1.5f ), + new ("Daisy", 4.3f ) ]; // Group Pet.Age values by the Math.Floor of the age. // Then project an anonymous type from each group // that consists of the key, the count of the group's // elements, and the minimum and maximum age in the group. var query = petsList.GroupBy( - pet => Math.Floor(pet.Age), + pet => (int)Math.Floor(pet.Age), pet => pet.Age, (baseAge, ages) => new { @@ -1118,30 +1117,30 @@ public static void GroupByEx4() static class GroupJoin { // - class Person + class Person(string name) { - public string Name { get; set; } + public string Name { get; set; } = name; } - class Pet + class Pet(string name, Person owner) { - public string Name { get; set; } - public Person Owner { get; set; } + public string Name { get; set; } = name; + public Person Owner { get; set; } = owner; } public static void GroupJoinEx1() { - Person magnus = new Person { Name = "Hedlund, Magnus" }; - Person terry = new Person { Name = "Adams, Terry" }; - Person charlotte = new Person { Name = "Weiss, Charlotte" }; + Person magnus = new("Hedlund, Magnus"); + Person terry = new("Adams, Terry"); + Person charlotte = new("Weiss, Charlotte"); - Pet barley = new Pet { Name = "Barley", Owner = terry }; - Pet boots = new Pet { Name = "Boots", Owner = terry }; - Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; + Pet barley = new("Barley", terry); + Pet boots = new("Boots", terry); + Pet whiskers = new("Whiskers", charlotte); + Pet daisy = new("Daisy", magnus); - List people = new List { magnus, terry, charlotte }; - List pets = new List { barley, boots, whiskers, daisy }; + List people = [magnus, terry, charlotte]; + List pets = [barley, boots, whiskers, daisy]; // Create a list where each element is an anonymous // type that contains a person's name and @@ -1185,27 +1184,28 @@ public static void GroupJoinEx1() // Uses query syntax. public static void GroupJoinEx2() { - Person magnus = new Person { Name = "Hedlund, Magnus" }; - Person terry = new Person { Name = "Adams, Terry" }; - Person charlotte = new Person { Name = "Weiss, Charlotte" }; + Person magnus = new("Hedlund, Magnus"); + Person terry = new("Adams, Terry"); + Person charlotte = new("Weiss, Charlotte"); - Pet barley = new Pet { Name = "Barley", Owner = terry }; - Pet boots = new Pet { Name = "Boots", Owner = terry }; - Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; + Pet barley = new("Barley", terry); + Pet boots = new("Boots", terry); + Pet whiskers = new("Whiskers", charlotte); + Pet daisy = new("Daisy", magnus); - List people = new List { magnus, terry, charlotte }; - List pets = new List { barley, boots, whiskers, daisy }; + List people = [magnus, terry, charlotte]; + List pets = [barley, boots, whiskers, daisy]; // - var query = from person in people - join pet in pets - on person equals pet.Owner into petCollection - select new - { - OwnerName = person.Name, - Pets = petCollection.Select(p => p.Name) - }; + var query = + from person in people + join pet in pets + on person equals pet.Owner into petCollection + select new + { + OwnerName = person.Name, + Pets = petCollection.Select(p => p.Name) + }; // foreach (var obj in query) @@ -1226,13 +1226,15 @@ on person equals pet.Owner into petCollection static void IntersectEx1() { // - int[] id1 = { 44, 26, 92, 30, 71, 38 }; - int[] id2 = { 39, 59, 83, 47, 26, 4, 30 }; + int[] id1 = [44, 26, 92, 30, 71, 38]; + int[] id2 = [39, 59, 83, 47, 26, 4, 30]; IEnumerable both = id1.Intersect(id2); foreach (int id in both) + { Console.WriteLine(id); + } /* This code produces the following output: @@ -1248,30 +1250,30 @@ static void IntersectEx1() static class Join { // - class Person + class Person(string name) { - public string Name { get; set; } + public string Name { get; set; } = name; } - class Pet + class Pet(string name, Person owner) { - public string Name { get; set; } - public Person Owner { get; set; } + public string Name { get; set; } = name; + public Person Owner { get; set; } = owner; } public static void JoinEx1() { - Person magnus = new Person { Name = "Hedlund, Magnus" }; - Person terry = new Person { Name = "Adams, Terry" }; - Person charlotte = new Person { Name = "Weiss, Charlotte" }; + Person magnus = new("Hedlund, Magnus"); + Person terry = new("Adams, Terry"); + Person charlotte = new("Weiss, Charlotte"); - Pet barley = new Pet { Name = "Barley", Owner = terry }; - Pet boots = new Pet { Name = "Boots", Owner = terry }; - Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; + Pet barley = new("Barley", terry); + Pet boots = new("Boots", terry); + Pet whiskers = new("Whiskers", charlotte); + Pet daisy = new("Daisy", magnus); - List people = new List { magnus, terry, charlotte }; - List pets = new List { barley, boots, whiskers, daisy }; + List people = [magnus, terry, charlotte]; + List pets = [barley, boots, whiskers, daisy]; // Create a list of Person-Pet pairs where // each element is an anonymous type that contains a @@ -1308,10 +1310,10 @@ public static void JoinEx1() static void LastEx1() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 67, 12, 19 ]; - int last = numbers.Last(); + int last = numbers[^1]; Console.WriteLine(last); @@ -1326,8 +1328,8 @@ static void LastEx1() static void LastEx2() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 67, 12, 19 ]; int last = numbers.Last(num => num > 80); @@ -1346,10 +1348,9 @@ static void LastEx2() static void LastOrDefaultEx1() { // - string[] fruits = { }; - string last = fruits.LastOrDefault(); - Console.WriteLine( - String.IsNullOrEmpty(last) ? "" : last); + string[] fruits = []; + var last = fruits.LastOrDefault(); + Console.WriteLine(last ?? ""); /* This code produces the following output: @@ -1362,7 +1363,7 @@ static void LastOrDefaultEx1() static void LastOrDefaultEx2() { // - double[] numbers = { 49.6, 52.3, 51.0, 49.4, 50.2, 48.3 }; + double[] numbers = [49.6, 52.3, 51.0, 49.4, 50.2, 48.3]; double last50 = numbers.LastOrDefault(n => Math.Round(n) == 50.0); @@ -1386,7 +1387,7 @@ The last number that rounds to 40 is . static void LastOrDefaultEx3() { // - List daysOfMonth = new List { }; + List daysOfMonth = []; // Setting the default value to 1 after the query. int lastDay1 = daysOfMonth.LastOrDefault(); @@ -1414,10 +1415,10 @@ The value of the lastDay2 variable is 1 public static void LongCountEx1() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; - long count = fruits.LongCount(); + long count = fruits.Length; Console.WriteLine("There are {0} fruits in the collection.", count); @@ -1432,17 +1433,18 @@ There are 6 fruits in the collection. static class LongCount { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void LongCountEx2() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; const int Age = 3; @@ -1464,9 +1466,9 @@ There are 2 animals over age 3. static void MaxEx1() { // - List longs = new List { 4294967296L, 466855135L, 81125L }; + List longs = [4294967296L, 466855135L, 81125L]; - long max = longs.Max(); + var max = longs.Max(); Console.WriteLine("The largest number is {0}.", max); @@ -1481,9 +1483,9 @@ The largest number is 4294967296. static void MaxEx2() { // - double?[] doubles = { null, 1.5E+104, 9E+103, -2E+103 }; + double?[] doubles = [null, 1.5E+104, 9E+103, -2E+103]; - double? max = doubles.Max(); + var max = doubles.Max(); Console.WriteLine("The largest number is {0}.", max); @@ -1502,10 +1504,11 @@ static class Max2 // IEnumerable /// This class implements IComparable to be able to /// compare one Pet to another Pet. /// - class Pet : IComparable + public class Pet(string name, int? age) : IComparable { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; } = name; + + public int Age { get; } = age ?? 0; /// /// Compares this Pet to another Pet by @@ -1515,37 +1518,42 @@ class Pet : IComparable /// -1 if this Pet is 'less' than the other Pet, /// 0 if they are equal, /// or 1 if this Pet is 'greater' than the other Pet. - int IComparable.CompareTo(Pet other) + public int CompareTo(Pet? other) { + if (other is null) return -1; int sumOther = other.Age + other.Name.Length; - int sumThis = this.Age + this.Name.Length; - - if (sumOther > sumThis) - return -1; - else if (sumOther == sumThis) - return 0; - else - return 1; + int sumThis = Age + Name.Length; + + return (sumOther > sumThis) + ? -1 + : (sumOther == sumThis) + ? 0 : 1; } } public static void MaxEx3() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ + new ("Barley", age:8 ), + new ("Boots", age:4 ), + new ("Whiskers", age:1 ) ]; - Pet max = pets.Max(); + //if (pets.Length > 0) + { + var maxage = pets.Max(p => p.Age); + var oldest = pets.First(p => p.Age == maxage); + var oldest2 = pets.OrderByDescending(p => p.Age) + .ThenBy(p => p.Name).First(); - Console.WriteLine( - "The 'maximum' animal is {0}.", - max.Name); + Console.WriteLine("The oldest animal is {0} at {1} years old.", + oldest, oldest.Age); + } } /* This code produces the following output: - The 'maximum' animal is Barley. + The oldest animal is Barley at 8 years old. */ // } @@ -1553,17 +1561,18 @@ public static void MaxEx3() static class Max10 // with a selector { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void MaxEx4() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; int max = pets.Max(pet => pet.Age + pet.Name.Length); @@ -1586,9 +1595,9 @@ The maximum pet age plus name length is 14. static void MinEx1() { // - double[] doubles = { 1.5E+104, 9E+103, -2E+103 }; + double[] doubles = [1.5E+104, 9E+103, -2E+103]; - double min = doubles.Min(); + var min = doubles.Min(); Console.WriteLine("The smallest number is {0}.", min); @@ -1603,9 +1612,9 @@ The smallest number is -2E+103. static void MinEx2() { // - int?[] grades = { 78, 92, null, 99, 37, 81 }; + int?[] grades = [78, 92, null, 99, 37, 81]; - int? min = grades.Min(); + var min = grades.Min(); Console.WriteLine("The lowest grade is {0}.", min); @@ -1624,10 +1633,10 @@ static class Min9 // IEnumerable /// This class implements IComparable in order to /// be able to compare different Pet objects. /// - class Pet : IComparable + class Pet(string name, int age) : IComparable { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; /// /// Compares this Pet's age to another Pet's age. @@ -1636,34 +1645,32 @@ class Pet : IComparable /// -1 if this Pet's age is smaller, /// 0 if the Pets' ages are equal, or /// 1 if this Pet's age is greater. - int IComparable.CompareTo(Pet other) - { - if (other.Age > this.Age) - return -1; - else if (other.Age == this.Age) - return 0; - else - return 1; - } + public int CompareTo(Pet? other) => + (other is null || other.Age > Age) + ? -1 + : (other.Age == Age) + ? 0 : 1; } public static void MinEx3() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; - Pet min = pets.Min(); + var min = pets.Min(p => p.Age); + var youngest = pets.First(p => p.Age == min); + //var youngest2 = pets.OrderByDescending(p => p.Age).ThenBy(p => p.Name).FirstOrDefault(); - Console.WriteLine( - "The 'minimum' animal is {0}.", - min.Name); + Console.WriteLine("The youngest animal is {0} at {1} years old.", + youngest.Name, youngest.Age); } /* This code produces the following output: - The 'minimum' animal is Whiskers. + The youngest animal is Whiskers at 1 years old. */ // } @@ -1671,19 +1678,20 @@ public static void MinEx3() static class Min10 // with a selector { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void MinEx4() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; - int min = pets.Min(pet => pet.Age); + var min = pets.Min(pet => pet.Age); Console.WriteLine("The youngest animal is age {0}.", min); } @@ -1701,15 +1709,13 @@ The youngest animal is age 1. static void OfTypeEx1() { // - System.Collections.ArrayList fruits = new() - { + System.Collections.ArrayList fruits = [ "Mango", "Orange", null, "Apple", 3.0, - "Banana" - }; + "Banana" ]; // Apply OfType() to the ArrayList. IEnumerable query1 = fruits.OfType(); @@ -1724,7 +1730,7 @@ static void OfTypeEx1() // Where() can be applied to the ArrayList type after calling OfType(). IEnumerable query2 = fruits.OfType().Where(fruit => - fruit.Contains('n', StringComparison.CurrentCultureIgnoreCase)); + fruit.Contains('n', StringComparison.CurrentCultureIgnoreCase)); Console.WriteLine("\nThe following strings contain 'n':"); foreach (string fruit in query2) @@ -1752,17 +1758,18 @@ static void OfTypeEx1() static class OrderBy { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void OrderByEx1() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ + new ("Barley", 8 ), + new ("Boots", 4 ), + new ("Whiskers", 1 ) ]; IEnumerable query = pets.OrderBy(pet => pet.Age); @@ -1783,52 +1790,30 @@ public static void OrderByEx1() } // - public class CaseInsensitiveCompare : IComparer - { - // Define a compare method that ignores case. - public int Compare(string s1, string s2) - { - return string.Compare(s1, s2, true); - } - } - - public class CaseSensitiveCompare : IComparer - { - // Define a compare method that does not ignore case. - public int Compare(string s1, string s2) - { - return string.Compare(s1, s2, false); - } - } - public static void OrderByIComparer() { - - string[] unsortedArray = { "one", "Four", "One", "First", "four", "first" }; + string[] unsortedArray = ["one", "Four", "One", "First", "four", "first"]; // Sort the array, ignoring case, and display the results. - var sortedArray = unsortedArray.OrderBy(a => a, new CaseInsensitiveCompare()); - Console.WriteLine("Case-insensitive sort of the strings " + - "in the array:"); - foreach (var element in sortedArray) + IOrderedEnumerable sortedArray = unsortedArray.OrderBy(a => a, StringComparer.OrdinalIgnoreCase); + Console.WriteLine("Case-insensitive sort of the strings in the array:"); + foreach (string element in sortedArray) { Console.WriteLine(element); } // Sort the array, not ignoring case, and display the results. - sortedArray = unsortedArray.OrderBy(a => a, new CaseSensitiveCompare()); - Console.WriteLine("\nCase-sensitive sort of the strings in " + - "the array:"); - foreach (var element in sortedArray) + sortedArray = unsortedArray.OrderBy(a => a, StringComparer.Ordinal); + Console.WriteLine("\nCase-sensitive sort of the strings in the array:"); + foreach (string element in sortedArray) { Console.WriteLine(element); } // Change the lambda expression to sort by the length of each string. - sortedArray = unsortedArray.OrderBy(a => (a.Length).ToString(), new CaseInsensitiveCompare()); - Console.WriteLine("\nSort based on the lengths of the strings in " + - "the array:"); - foreach (var element in sortedArray) + sortedArray = unsortedArray.OrderBy(a => a.Length); + Console.WriteLine("\nSort based on the lengths of the strings in the array:"); + foreach (string element in sortedArray) { Console.WriteLine(element); } @@ -1904,19 +1889,16 @@ public int Compare(decimal d1, decimal d2) fractional2 = d2; } - if (fractional1 == fractional2) - return Decimal.Compare(d1, d2); - else if (fractional1 > fractional2) - return 1; - else - return -1; + return (fractional1 == fractional2) + ? decimal.Compare(d1, d2) + : (fractional1 > fractional2) + ? 1 : -1; } } public static void OrderByDescendingEx1() { - List decimals = - new List { 6.2m, 8.3m, 0.5m, 1.3m, 6.3m, 9.7m }; + List decimals = [6.2m, 8.3m, 0.5m, 1.3m, 6.3m, 9.7m]; IEnumerable query = decimals.OrderByDescending(num => @@ -1980,7 +1962,7 @@ static void RepeatEx1() IEnumerable strings = Enumerable.Repeat("I like programming.", 15); - foreach (String str in strings) + foreach (string str in strings) { Console.WriteLine(str); } @@ -2012,7 +1994,7 @@ I like programming. static void ReverseEx1() { // - char[] apple = { 'a', 'p', 'p', 'l', 'e' }; + char[] apple = ['a', 'p', 'p', 'l', 'e']; char[] reversed = apple.Reverse().ToArray(); @@ -2062,12 +2044,12 @@ static void SelectEx1() static void SelectEx2() { // - string[] fruits = { "apple", "banana", "mango", "orange", - "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", "orange", + "passionfruit", "grape" ]; var query = fruits.Select((fruit, index) => - new { index, str = fruit.Substring(0, index) }); + new { index, str = fruit[..index] }); foreach (var obj in query) { @@ -2092,21 +2074,18 @@ static void SelectEx2() static class SelectMany1 { // - class PetOwner + class PetOwner(string name, List pets) { - public string Name { get; set; } - public List Pets { get; set; } + public string Name { get; set; } = name; + public List Pets { get; set; } = pets; } public static void SelectManyEx1() { - PetOwner[] petOwners = - { new PetOwner { Name="Higa, Sidney", - Pets = new List{ "Scruffy", "Sam" } }, - new PetOwner { Name="Ashkenazi, Ronen", - Pets = new List{ "Walker", "Sugar" } }, - new PetOwner { Name="Price, Vernette", - Pets = new List{ "Scratches", "Diesel" } } }; + PetOwner[] petOwners = [ + new ("Higa, Sidney", ["Scruffy", "Sam"] ), + new ("Ashkenazi, Ronen", ["Walker", "Sugar"] ), + new ("Price, Vernette", ["Scratches", "Diesel"] ) ]; // Query using SelectMany(). IEnumerable query1 = petOwners.SelectMany(petOwner => petOwner.Pets); @@ -2123,15 +2102,14 @@ public static void SelectManyEx1() // This code shows how to use Select() // instead of SelectMany(). - IEnumerable> query2 = + IEnumerable> query2 = petOwners.Select(petOwner => petOwner.Pets); Console.WriteLine("\nUsing Select():"); - // Notice that two foreach loops are required to - // iterate through the results - // because the query returns a collection of arrays. - foreach (List petList in query2) + // Notice that two foreach loops are required to iterate through + // the results because the query returns a collection of arrays. + foreach (List petList in query2) { foreach (string pet in petList) { @@ -2168,23 +2146,19 @@ Using Select(): static class SelectMany2 { // - class PetOwner + class PetOwner(string name, List pets) { - public string Name { get; set; } - public List Pets { get; set; } + public string Name { get; set; } = name; + public List Pets { get; set; } = pets; } public static void SelectManyEx2() { - PetOwner[] petOwners = - { new PetOwner { Name="Higa, Sidney", - Pets = new List{ "Scruffy", "Sam" } }, - new PetOwner { Name="Ashkenazi, Ronen", - Pets = new List{ "Walker", "Sugar" } }, - new PetOwner { Name="Price, Vernette", - Pets = new List{ "Scratches", "Diesel" } }, - new PetOwner { Name="Hines, Patrick", - Pets = new List{ "Dusty" } } }; + PetOwner[] petOwners = [ + new ("Higa, Sidney", ["Scruffy", "Sam"] ), + new ("Ashkenazi, Ronen", ["Walker", "Sugar"] ), + new ("Price, Vernette", ["Scratches", "Diesel"] ), + new ("Hines, Patrick", ["Dusty"] ) ]; // Project the items in the array by appending the index // of each PetOwner to each pet's name in that petOwner's @@ -2214,35 +2188,31 @@ public static void SelectManyEx2() static class SelectMany3 { // - class PetOwner + class PetOwner(string name, List pets) { - public string Name { get; set; } - public List Pets { get; set; } + public string Name { get; set; } = name; + public List Pets { get; set; } = pets; } public static void SelectManyEx3() { - PetOwner[] petOwners = - { new PetOwner { Name="Higa", - Pets = new List{ "Scruffy", "Sam" } }, - new PetOwner { Name="Ashkenazi", - Pets = new List{ "Walker", "Sugar" } }, - new PetOwner { Name="Price", - Pets = new List{ "Scratches", "Diesel" } }, - new PetOwner { Name="Hines", - Pets = new List{ "Dusty" } } }; + PetOwner[] petOwners = [ + new ("Higa", ["Scruffy", "Sam"] ), + new ("Ashkenazi", ["Walker", "Sugar"] ), + new ("Price", ["Scratches", "Diesel"] ), + new ("Hines", ["Dusty"] ) ]; // Project the pet owner's name and the pet's name. - var query = - petOwners - .SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName }) - .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S")) + var query = petOwners + .SelectMany(petOwner => petOwner.Pets, + (petOwner, petName) => new { petOwner, petName }) + .Where(ownerAndPet => ownerAndPet.petName.StartsWith('S')) .Select(ownerAndPet => - new - { - Owner = ownerAndPet.petOwner.Name, - Pet = ownerAndPet.petName - } + new + { + Owner = ownerAndPet.petOwner.Name, + Pet = ownerAndPet.petName + } ); // Print the results. @@ -2266,20 +2236,20 @@ public static void SelectManyEx3() static class SequenceEqual1 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void SequenceEqualEx1() { - Pet pet1 = new Pet { Name = "Turbo", Age = 2 }; - Pet pet2 = new Pet { Name = "Peanut", Age = 8 }; + Pet pet1 = new("Turbo", 2); + Pet pet2 = new("Peanut", 8); // Create two lists of pets. - List pets1 = new List { pet1, pet2 }; - List pets2 = new List { pet1, pet2 }; + List pets1 = [pet1, pet2]; + List pets2 = [pet1, pet2]; bool equal = pets1.SequenceEqual(pets2); @@ -2299,22 +2269,22 @@ The lists are equal. static class SequenceEqual2 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void SequenceEqualEx2() { - Pet pet1 = new Pet() { Name = "Turbo", Age = 2 }; - Pet pet2 = new Pet() { Name = "Peanut", Age = 8 }; + Pet pet1 = new("Turbo", 2); + Pet pet2 = new("Peanut", 8); // Create two lists of pets. - List pets1 = new List { pet1, pet2 }; - List pets2 = - new List { new Pet { Name = "Turbo", Age = 2 }, - new Pet { Name = "Peanut", Age = 8 } }; + List pets1 = [pet1, pet2]; + List pets2 = [ + new ( "Turbo", 2 ), + new ( "Peanut", 8 ) ]; bool equal = pets1.SequenceEqual(pets2); @@ -2334,7 +2304,7 @@ The lists are not equal. static void SingleEx1() { // - string[] fruits1 = { "orange" }; + string[] fruits1 = ["orange"]; string fruit1 = fruits1.Single(); @@ -2348,8 +2318,8 @@ static void SingleEx1() // // - string[] fruits2 = { "orange", "apple" }; - string fruit2 = null; + string[] fruits2 = ["orange", "apple"]; + string? fruit2 = null; try { @@ -2360,7 +2330,7 @@ static void SingleEx1() Console.WriteLine("The collection does not contain exactly one element."); } - Console.WriteLine(fruit2); + Console.WriteLine(fruit2 ?? "none"); /* This code produces the following output: @@ -2376,8 +2346,8 @@ The collection does not contain exactly one element. static void SingleEx2() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; string fruit1 = fruits.Single(fruit => fruit.Length > 10); @@ -2391,20 +2361,17 @@ static void SingleEx2() // // - string fruit2 = null; - try { - fruit2 = fruits.Single(fruit => fruit.Length > 15); + var fruit2 = fruits.Single(fruit => fruit.Length > 15); + Console.WriteLine("sole long Name = {0}", fruit2); } catch (System.InvalidOperationException) { - Console.WriteLine(@"The collection does not contain exactly - one element whose length is greater than 15."); + Console.WriteLine("The collection does not contain exactly\n" + + "one element whose length is greater than 15."); } - Console.WriteLine(fruit2); - // This code produces the following output: // // The collection does not contain exactly @@ -2417,9 +2384,9 @@ static void SingleEx2() static void SingleOrDefaultEx1() { // - string[] fruits1 = { "orange" }; + string[] fruits1 = ["orange"]; - string fruit1 = fruits1.SingleOrDefault(); + var fruit1 = fruits1.SingleOrDefault(); Console.WriteLine(fruit1); @@ -2431,12 +2398,11 @@ static void SingleOrDefaultEx1() // // - string[] fruits2 = { }; + string[] fruits2 = []; - string fruit2 = fruits2.SingleOrDefault(); + var fruit2 = fruits2.SingleOrDefault(); - Console.WriteLine( - String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2); + Console.WriteLine(fruit2 ?? "No such string!"); /* This code produces the following output: @@ -2449,12 +2415,12 @@ No such string! static void SingleOrDefaultEx2() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; - string fruit1 = fruits.SingleOrDefault(fruit => fruit.Length > 10); + var fruit1 = fruits.SingleOrDefault(fruit => fruit.Length > 10); - Console.WriteLine(fruit1); + Console.WriteLine(fruit1 ?? "none"); /* This code produces the following output: @@ -2464,11 +2430,11 @@ static void SingleOrDefaultEx2() // // - string fruit2 = + var fruit2 = fruits.SingleOrDefault(fruit => fruit.Length > 15); Console.WriteLine( - String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2); + fruit2 ?? "No such string!"); /* This code produces the following output: @@ -2481,7 +2447,7 @@ No such string! static void SingleOrDefaultEx3() { // - int[] pageNumbers = { }; + int[] pageNumbers = []; // Setting the default value to 1 after the query. int pageNumber1 = pageNumbers.SingleOrDefault(); @@ -2509,7 +2475,7 @@ The value of the pageNumber2 variable is 1 static void SkipEx1() { // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; Console.WriteLine("All grades except the first three:"); foreach (int grade in grades.Skip(3)) @@ -2534,7 +2500,7 @@ static void SkipEx1() static void SkipWhileEx1() { // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; IEnumerable lowerGrades = grades @@ -2561,8 +2527,8 @@ static void SkipWhileEx1() static void SkipWhileEx2() { // - int[] amounts = { 5000, 2500, 9000, 8000, - 6500, 4000, 1500, 5500 }; + int[] amounts = [ 5000, 2500, 9000, 8000, + 6500, 4000, 1500, 5500 ]; IEnumerable query = amounts.SkipWhile((amount, index) => amount > index * 1000); @@ -2587,20 +2553,19 @@ static void SkipWhileEx2() static class Sum9 { // - class Package + class Package(string company, double weight) { - public string Company { get; set; } - public double Weight { get; set; } + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; } public static void SumEx1() { - List packages = - new List - { new Package { Company = "Coho Vineyard", Weight = 25.2 }, - new Package { Company = "Lucerne Publishing", Weight = 18.7 }, - new Package { Company = "Wingtip Toys", Weight = 6.0 }, - new Package { Company = "Adventure Works", Weight = 33.8 } }; + List packages = [ + new ("Coho Vineyard", 25.2 ), + new ("Lucerne Publishing", 18.7 ), + new ("Wingtip Toys", 6.0 ), + new ("Adventure Works", 33.8 ) ]; double totalWeight = packages.Sum(pkg => pkg.Weight); @@ -2618,7 +2583,7 @@ public static void SumEx1() static void SumEx2() { // - List numbers = new List { 43.68F, 1.25F, 583.7F, 6.5F }; + List numbers = [43.68F, 1.25F, 583.7F, 6.5F]; float sum = numbers.Sum(); @@ -2635,7 +2600,7 @@ The sum of the numbers is 635.13. static void SumEx3() { // - float?[] points = { null, 0, 92.83F, null, 100.0F, 37.46F, 81.1F }; + float?[] points = [null, 0, 92.83F, null, 100.0F, 37.46F, 81.1F]; float? sum = points.Sum(); @@ -2655,7 +2620,7 @@ static void SumEx3() static void TakeEx1() { // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; IEnumerable topThreeGrades = grades.OrderByDescending(grade => grade).Take(3); @@ -2681,11 +2646,11 @@ static void TakeEx1() static void TakeWhileEx1() { // - string[] fruits = { "apple", "banana", "mango", "orange", - "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", "orange", + "passionfruit", "grape" ]; IEnumerable query = - fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0); + fruits.TakeWhile(fruit => string.Compare("orange", fruit, true) != 0); foreach (string fruit in query) { @@ -2705,8 +2670,8 @@ static void TakeWhileEx1() static void TakeWhileEx2() { // - string[] fruits = { "apple", "passionfruit", "banana", "mango", - "orange", "blueberry", "grape", "strawberry" }; + string[] fruits = [ "apple", "passionfruit", "banana", "mango", + "orange", "blueberry", "grape", "strawberry" ]; IEnumerable query = fruits.TakeWhile((fruit, index) => fruit.Length >= index); @@ -2735,8 +2700,8 @@ static void TakeWhileEx2() static void ThenByEx1() { // - string[] fruits = { "grape", "passionfruit", "banana", "mango", - "orange", "raspberry", "apple", "blueberry" }; + string[] fruits = [ "grape", "passionfruit", "banana", "mango", + "orange", "raspberry", "apple", "blueberry" ]; // Sort the strings first by their length and then //alphabetically by passing the identity selector function. @@ -2769,24 +2734,15 @@ static void ThenByEx1() static class ThenByDescending { // - public class CaseInsensitiveComparer : IComparer - { - public int Compare(string x, string y) - { - return string.Compare(x, y, true); - } - } - public static void ThenByDescendingEx1() { - string[] fruits = { "apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE" }; + string[] fruits = ["apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE"]; // Sort the strings first ascending by their length and // then descending using a custom case insensitive comparer. - IEnumerable query = - fruits + IEnumerable query = fruits .OrderBy(fruit => fruit.Length) - .ThenByDescending(fruit => fruit, new CaseInsensitiveComparer()); + .ThenByDescending(fruit => fruit, StringComparer.OrdinalIgnoreCase); foreach (string fruit in query) { @@ -2814,20 +2770,19 @@ public static void ThenByDescendingEx1() static class ToArray { // - class Package + class Package(string company, double weight) { - public string Company { get; set; } - public double Weight { get; set; } + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; } public static void ToArrayEx1() { - List packages = - new List - { new Package { Company = "Coho Vineyard", Weight = 25.2 }, - new Package { Company = "Lucerne Publishing", Weight = 18.7 }, - new Package { Company = "Wingtip Toys", Weight = 6.0 }, - new Package { Company = "Adventure Works", Weight = 33.8 } }; + List packages = [ + new ("Coho Vineyard", 25.2 ), + new ("Lucerne Publishing", 18.7 ), + new ("Wingtip Toys", 6.0 ), + new ("Adventure Works", 33.8 ) ]; string[] companies = packages.Select(pkg => pkg.Company).ToArray(); @@ -2854,21 +2809,20 @@ Adventure Works static class ToDictionary { // - class Package + class Package(string company, double weight, long trackingNumber) { - public string Company { get; set; } - public double Weight { get; set; } - public long TrackingNumber { get; set; } + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; + public long TrackingNumber { get; set; } = trackingNumber; } public static void ToDictionaryEx1() { - List packages = - new List - { new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L }, - new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L }, - new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L }, - new Package { Company = "Adventure Works", Weight = 33.8, TrackingNumber = 4665518773L } }; + List packages = [ + new ("Coho Vineyard", 25.2, 89453312L ), + new ("Lucerne Publishing", 18.7, 89112755L ), + new ("Wingtip Toys", 6.0, 299456122L ), + new ("Adventure Works", 33.8, 4665518773L ) ]; // Create a Dictionary of Package objects, // using TrackingNumber as the key. @@ -2901,8 +2855,8 @@ public static void ToDictionaryEx1() static void ToListEx1() { // - string[] fruits = { "apple", "passionfruit", "banana", "mango", - "orange", "blueberry", "grape", "strawberry" }; + string[] fruits = [ "apple", "passionfruit", "banana", "mango", + "orange", "blueberry", "grape", "strawberry" ]; List lengths = fruits.Select(fruit => fruit.Length).ToList(); @@ -2932,35 +2886,28 @@ static void ToListEx1() static class ToLookup { // - class Package + class Package(string company, double weight, long trackingNumber) { - public string Company { get; set; } - public double Weight { get; set; } - public long TrackingNumber { get; set; } + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; + public long TrackingNumber { get; set; } = trackingNumber; } public static void ToLookupEx1() { // Create a list of Packages. - List packages = - new List - { new Package { Company = "Coho Vineyard", - Weight = 25.2, TrackingNumber = 89453312L }, - new Package { Company = "Lucerne Publishing", - Weight = 18.7, TrackingNumber = 89112755L }, - new Package { Company = "Wingtip Toys", - Weight = 6.0, TrackingNumber = 299456122L }, - new Package { Company = "Contoso Pharmaceuticals", - Weight = 9.3, TrackingNumber = 670053128L }, - new Package { Company = "Wide World Importers", - Weight = 33.8, TrackingNumber = 4665518773L } }; + List packages = [ + new ("Coho Vineyard", 25.2, 89453312L ), + new ("Lucerne Publishing", 18.7, 89112755L ), + new ("Wingtip Toys", 6.0, 299456122L ), + new ("Contoso Pharmaceuticals", 9.3, 670053128L ), + new ("Wide World Importers", 33.8, 4665518773L ) ]; // Create a Lookup to organize the packages. // Use the first character of Company as the key value. // Select Company appended to TrackingNumber // as the element values of the Lookup. - ILookup lookup = - packages + ILookup lookup = packages .ToLookup(p => p.Company[0], p => p.Company + " " + p.TrackingNumber); @@ -2972,7 +2919,9 @@ public static void ToLookupEx1() // Iterate through each value in the // IGrouping and print its value. foreach (string str in packageGroup) + { Console.WriteLine(" {0}", str); + } } } @@ -2996,8 +2945,8 @@ Wide World Importers 4665518773 static void UnionEx1() { // - int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 }; - int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 }; + int[] ints1 = [5, 3, 9, 7, 5, 9, 3, 7]; + int[] ints2 = [8, 3, 6, 4, 4, 9, 1, 0]; IEnumerable union = ints1.Union(ints2); @@ -3021,9 +2970,8 @@ 5 3 9 7 8 6 4 1 0 static void WhereEx1() { // - List fruits = - new List { "apple", "passionfruit", "banana", "mango", - "orange", "blueberry", "grape", "strawberry" }; + List fruits = [ "apple", "passionfruit", "banana", "mango", + "orange", "blueberry", "grape", "strawberry" ]; IEnumerable query = fruits.Where(fruit => fruit.Length < 6); @@ -3044,7 +2992,7 @@ static void WhereEx1() static void WhereEx2() { // - int[] numbers = { 0, 30, 20, 15, 90, 85, 40, 75 }; + int[] numbers = [0, 30, 20, 15, 90, 85, 40, 75]; IEnumerable query = numbers.Where((number, index) => number <= index * 10); @@ -3069,13 +3017,15 @@ static void WhereEx2() static void ZipEx() { // - int[] numbers = { 1, 2, 3, 4 }; - string[] words = { "one", "two", "three" }; + int[] numbers = [1, 2, 3, 4]; + string[] words = ["one", "two", "three"]; - var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second); + IEnumerable numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second); - foreach (var item in numbersAndWords) + foreach (string item in numbersAndWords) + { Console.WriteLine(item); + } // This code produces the following output: @@ -3091,10 +3041,10 @@ static void AppendEx() { // // Creating a list of numbers - List numbers = new List { 1, 2, 3, 4 }; + List numbers = [1, 2, 3, 4]; // Trying to append any value of the same type - numbers.Append(5); + _ = numbers.Append(5); // It doesn't work because the original list has not been changed Console.WriteLine(string.Join(", ", numbers)); @@ -3103,7 +3053,7 @@ static void AppendEx() Console.WriteLine(string.Join(", ", numbers.Append(5))); // If you prefer, you can create a new list explicitly - List newNumbers = numbers.Append(5).ToList(); + List newNumbers = [.. numbers, 5]; // And then write to the console output Console.WriteLine(string.Join(", ", newNumbers)); @@ -3122,10 +3072,10 @@ static void PrependEx() { // // Creating a list of numbers - List numbers = new List { 1, 2, 3, 4 }; + List numbers = [1, 2, 3, 4]; // Trying to prepend any value of the same type - numbers.Prepend(0); + _ = numbers.Prepend(0); // It doesn't work because the original list has not been changed Console.WriteLine(string.Join(", ", numbers)); @@ -3153,7 +3103,7 @@ static void SkipLast() { #if NETCOREAPP // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; IEnumerable topGrades = grades.OrderByDescending(g => g).SkipLast(3); @@ -3182,7 +3132,7 @@ static void TakeLast() { #if NETCOREAPP // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; IEnumerable bottomThreeGrades = grades.OrderByDescending(grade => grade).TakeLast(3); diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj b/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj index ce892295f4f..dd998a3c7af 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/Comparers.csproj @@ -1,9 +1,11 @@ - + Exe - net6.0;net472 - Program + net8.0;net472 + enable + Comparers.Program + latest diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs b/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs index 7f33762c739..e9622811f68 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/CustomComparer.cs @@ -2,30 +2,26 @@ using System.Collections.Generic; using System.Linq; +namespace Comparers; + // -public class Product +public class Product(string name, int code) { - public string Name { get; set; } - public int Code { get; set; } + public string Name { get; set; } = name; + public int Code { get; set; } = code; } // Custom comparer for the Product class class ProductComparer : IEqualityComparer { // Products are equal if their names and product numbers are equal. - public bool Equals(Product x, Product y) - { - + public bool Equals(Product? x, Product? y) => //Check whether the compared objects reference the same data. - if (Object.ReferenceEquals(x, y)) return true; - - //Check whether any of the compared objects is null. - if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) - return false; - - //Check whether the products' properties are equal. - return x.Code == y.Code && x.Name == y.Name; - } + ReferenceEquals(x, y) || + ( x is not null && //Check if any of the compared objects is null + y is not null && + x.Code == y.Code && //Check if the products' properties are equal. + x.Name == y.Name); // If Equals() returns true for a pair of objects // then GetHashCode() must return the same value for these objects. @@ -33,13 +29,13 @@ public bool Equals(Product x, Product y) public int GetHashCode(Product product) { //Check whether the object is null - if (Object.ReferenceEquals(product, null)) return 0; + if (product is null) return 0; - //Get hash code for the Name field if it is not null. - int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode(); + //Get hash code for the Name field + var hashProductName = product.Name.GetHashCode(); - //Get hash code for the Code field. - int hashProductCode = product.Code.GetHashCode(); + //Get hash code for the Code field + var hashProductCode = product.Code.GetHashCode(); //Calculate the hash code for the product. return hashProductName ^ hashProductCode; @@ -47,16 +43,18 @@ public int GetHashCode(Product product) } // -class Program +static class Program { - static void Main(string[] args) + static void Main() { // - Product[] store1 = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 } }; + Product[] store1 = [ + new ("apple",9 ), + new ("orange",4 ) ]; - Product[] store2 = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "lemon", Code = 12 } }; + Product[] store2 = [ + new ("apple",9 ), + new ("lemon",12 ) ]; // Get the products from the first array // that have duplicates in the second array. @@ -64,8 +62,10 @@ static void Main(string[] args) IEnumerable duplicates = store1.Intersect(store2, new ProductComparer()); - foreach (var product in duplicates) + foreach (Product product in duplicates) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -74,11 +74,13 @@ apple 9 // // - Product[] store10 = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 } }; + Product[] store10 = [ + new ("apple",9 ), + new ("orange",4 ) ]; - Product[] store20 = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "lemon", Code = 12 } }; + Product[] store20 = [ + new ("apple",9 ), + new ("lemon",12 ) ]; //Get the products from the both arrays //excluding duplicates. @@ -87,7 +89,9 @@ apple 9 store10.Union(store20, new ProductComparer()); foreach (Product product in union) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -99,18 +103,21 @@ lemon 12 // // - Product[] products = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 }, - new Product { Name = "apple", Code = 9 }, - new Product { Name = "lemon", Code = 12 } }; + Product[] products = [ + new ("apple",9 ), + new ("orange",4 ), + new ("apple",9 ), + new ("lemon",12 ) ]; // Exclude duplicates. IEnumerable noduplicates = products.Distinct(new ProductComparer()); - foreach (var product in noduplicates) + foreach (Product product in noduplicates) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -121,17 +128,18 @@ lemon 12 // // - Product[] fruits = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 }, - new Product { Name = "lemon", Code = 12 } }; + Product[] fruits = [ + new ("apple",9 ), + new ("orange",4 ), + new ("lemon",12 ) ]; - Product apple = new Product { Name = "apple", Code = 9 }; - Product kiwi = new Product { Name = "kiwi", Code = 8 }; + Product apple = new("apple", 9); + Product kiwi = new("kiwi", 8); - ProductComparer prodc = new ProductComparer(); + ProductComparer prodc = new(); - bool hasApple = fruits.Contains(apple, prodc); - bool hasKiwi = fruits.Contains(kiwi, prodc); + var hasApple = fruits.Contains(apple, prodc); + var hasKiwi = fruits.Contains(kiwi, prodc); Console.WriteLine("Apple? " + hasApple); Console.WriteLine("Kiwi? " + hasKiwi); @@ -146,11 +154,12 @@ lemon 12 // // - Product[] fruits1 = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 }, - new Product { Name = "lemon", Code = 12 } }; + Product[] fruits1 = [ + new ("apple",9 ), + new ("orange",4 ), + new ("lemon",12 ) ]; - Product[] fruits2 = { new Product { Name = "apple", Code = 9 } }; + Product[] fruits2 = [new("apple", 9)]; // Get all the elements from the first array // except for the elements from the second array. @@ -158,8 +167,10 @@ lemon 12 IEnumerable except = fruits1.Except(fruits2, new ProductComparer()); - foreach (var product in except) + foreach (Product product in except) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -172,13 +183,15 @@ lemon 12 // - Product[] storeA = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 } }; + Product[] storeA = [ + new ("apple",9 ), + new ("orange",4 ) ]; - Product[] storeB = { new Product { Name = "apple", Code = 9 }, - new Product { Name = "orange", Code = 4 } }; + Product[] storeB = [ + new ("apple",9 ), + new ("orange",4 ) ]; - bool equalAB = storeA.SequenceEqual(storeB, new ProductComparer()); + var equalAB = storeA.SequenceEqual(storeB, new ProductComparer()); Console.WriteLine("Equal? " + equalAB); @@ -190,6 +203,6 @@ lemon 12 // - Console.ReadLine(); + _ = Console.ReadLine(); } } diff --git a/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs b/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs index 3ecc5c2cf63..285acab8db3 100644 --- a/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs +++ b/snippets/csharp/System.Linq/Enumerable/Comparers/EncapsulatedComparer.cs @@ -2,19 +2,21 @@ using System.Collections.Generic; using System.Linq; +namespace Comparers; + // -public class MyProduct : IEquatable +public class MyProduct(string name, int code) : IEquatable { - public string Name { get; set; } - public int Code { get; set; } + public string Name { get; set; } = name; + public int Code { get; set; } = code; - public bool Equals(MyProduct other) + public bool Equals(MyProduct? other) { //Check whether the compared object is null. - if (Object.ReferenceEquals(other, null)) return false; + if (other is null) return false; //Check whether the compared object references the same data. - if (Object.ReferenceEquals(this, other)) return true; + if (ReferenceEquals(this, other)) return true; //Check whether the products' properties are equal. return Code.Equals(other.Code) && Name.Equals(other.Name); @@ -25,32 +27,35 @@ public bool Equals(MyProduct other) public override int GetHashCode() { + //Get hash code for the Name field + var hashProductName = Name.GetHashCode(); - //Get hash code for the Name field if it is not null. - int hashProductName = Name == null ? 0 : Name.GetHashCode(); - - //Get hash code for the Code field. - int hashProductCode = Code.GetHashCode(); + //Get hash code for the Code field + var hashProductCode = Code.GetHashCode(); //Calculate the hash code for the product. return hashProductName ^ hashProductCode; } + + public override bool Equals(object? obj) => Equals(obj as MyProduct); } // -class Program1 +static class Program1 { - static void Main(string[] args) + static void Main() { // This snippet is different than #2 by using ProductA (not Product). // Some samples here need to use ProductA in conjunction with // ProductComparer, which implements IEqualityComparer (not IEquatable). // - ProductA[] store1 = { new ProductA { Name = "apple", Code = 9 }, - new ProductA { Name = "orange", Code = 4 } }; + ProductA[] store1 = [ + new ("apple", 9 ), + new ("orange", 4 ) ]; - ProductA[] store2 = { new ProductA { Name = "apple", Code = 9 }, - new ProductA { Name = "lemon", Code = 12 } }; + ProductA[] store2 = [ + new ("apple", 9 ), + new ("lemon", 12 ) ]; // // @@ -60,8 +65,10 @@ static void Main(string[] args) IEnumerable duplicates = store1.Intersect(store2); - foreach (var product in duplicates) + foreach (ProductA product in duplicates) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -74,10 +81,12 @@ apple 9 //excluding duplicates. IEnumerable union = - store1.Union(store2); + store1.Union(store2); - foreach (var product in union) + foreach (ProductA product in union) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -89,18 +98,21 @@ lemon 12 // // - MyProduct[] products = { new MyProduct { Name = "apple", Code = 9 }, - new MyProduct { Name = "orange", Code = 4 }, - new MyProduct { Name = "apple", Code = 9 }, - new MyProduct { Name = "lemon", Code = 12 } }; + MyProduct[] products = [ + new ("apple", 9 ), + new ("orange", 4 ), + new ("apple", 9 ), + new ("lemon", 12 ) ]; // Exclude duplicates. IEnumerable noduplicates = products.Distinct(); - foreach (var product in noduplicates) + foreach (MyProduct product in noduplicates) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -111,11 +123,12 @@ lemon 12 // // - ProductA[] fruits1 = { new ProductA { Name = "apple", Code = 9 }, - new ProductA { Name = "orange", Code = 4 }, - new ProductA { Name = "lemon", Code = 12 } }; + ProductA[] fruits1 = [ + new ("apple", 9 ), + new ("orange", 4 ), + new ("lemon", 12 ) ]; - ProductA[] fruits2 = { new ProductA { Name = "apple", Code = 9 } }; + ProductA[] fruits2 = [new("apple", 9)]; // Get all the elements from the first array // except for the elements from the second array. @@ -123,8 +136,10 @@ lemon 12 IEnumerable except = fruits1.Except(fruits2); - foreach (var product in except) + foreach (ProductA product in except) + { Console.WriteLine(product.Name + " " + product.Code); + } /* This code produces the following output: @@ -136,13 +151,15 @@ lemon 12 // - ProductA[] storeA = { new ProductA { Name = "apple", Code = 9 }, - new ProductA { Name = "orange", Code = 4 } }; + ProductA[] storeA = [ + new ("apple", 9 ), + new ("orange", 4 ) ]; - ProductA[] storeB = { new ProductA { Name = "apple", Code = 9 }, - new ProductA { Name = "orange", Code = 4 } }; + ProductA[] storeB = [ + new ("apple", 9 ), + new ("orange", 4 ) ]; - bool equalAB = storeA.SequenceEqual(storeB); + var equalAB = storeA.SequenceEqual(storeB); Console.WriteLine("Equal? " + equalAB); @@ -156,20 +173,17 @@ lemon 12 } // - public class ProductA : IEquatable + public class ProductA(string name, int code) : IEquatable { - public string Name { get; set; } - public int Code { get; set; } + public string Name { get; set; } = name; + public int Code { get; set; } = code; - public bool Equals(ProductA other) - { - if (other is null) - return false; - - return this.Name == other.Name && this.Code == other.Code; - } + public bool Equals(ProductA? other) => + other is not null && + Name == other.Name && + Code == other.Code; - public override bool Equals(object obj) => Equals(obj as ProductA); + public override bool Equals(object? obj) => Equals(obj as ProductA); public override int GetHashCode() => (Name, Code).GetHashCode(); } // diff --git a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj new file mode 100644 index 00000000000..b2438766608 --- /dev/null +++ b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/IGrouping.csproj @@ -0,0 +1,9 @@ + + + + Library + net8.0 + enable + + + \ No newline at end of file diff --git a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/Project.csproj b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/Project.csproj deleted file mode 100644 index c02dc5044e7..00000000000 --- a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/Project.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Library - net6.0 - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/igrouping.cs b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/igrouping.cs index 955d07ed9bc..f7857290b08 100644 --- a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/igrouping.cs +++ b/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/igrouping.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Linq; //using System.Reflection; @@ -8,28 +7,30 @@ namespace SequenceExamples { static class IGrouping { - static void Main(string[] args) + static void Main() { //Console.WriteLine("\n"); //GroupKey(); EnumerateGroup(); } - private static void EnumerateGroup() + static void EnumerateGroup() { // // Get an IGrouping object. IGrouping group = - typeof(String).GetMembers(). - GroupBy(member => member.MemberType). - First(); + typeof(string).GetMembers() + .GroupBy(member => member.MemberType) + .First(); // Output the key of the IGrouping, then iterate // through each value in the sequence of values // of the IGrouping and output its Name property. Console.WriteLine("\nValues that have the key '{0}':", group.Key); foreach (System.Reflection.MemberInfo mi in group) + { Console.WriteLine(mi.Name); + } // The output is similar to: @@ -54,17 +55,19 @@ private static void EnumerateGroup() // } - private static void GroupKey() + static void GroupKey() { // // Get a sequence of IGrouping objects. IEnumerable> memberQuery = - typeof(String).GetMembers(). + typeof(string).GetMembers(). GroupBy(member => member.MemberType); // Output the key of each IGrouping object and the count of values. foreach (IGrouping group in memberQuery) + { Console.WriteLine("(Key) {0} (Member count) {1}", group.Key, group.Count()); + } // The output is similar to: // (Key) Method (Member count) 113 @@ -75,10 +78,10 @@ private static void GroupKey() // } - private static void Test() + static void Test() { IOrderedEnumerable> memberQuery = - typeof(String).GetMembers(). + typeof(string).GetMembers(). GroupBy(member => member.MemberType). OrderBy(group => group.Count()); @@ -86,7 +89,9 @@ private static void Test() { Console.WriteLine("\n(Key) {0}", group.Key); foreach (System.Reflection.MemberInfo mi in group) + { Console.WriteLine(mi.Name); + } } } } diff --git a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs index 7c89e4efe09..d0e8beab18d 100644 --- a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs +++ b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Linq; @@ -7,27 +6,25 @@ namespace SequenceExamples { static class ILookup { - static void Main(string[] args) - { - ILookupExample(); - } + static void Main() => ILookupExample(); // - class Package + class Package(string company, double weight, long trackingNumber) { - public string Company { get; set; } - public double Weight { get; set; } - public long TrackingNumber { get; set; } + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; + public long TrackingNumber { get; set; } = trackingNumber; } public static void ILookupExample() { // Create a list of Packages to put into an ILookup data structure. - List packages = new List { new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L }, - new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L }, - new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L }, - new Package { Company = "Contoso Pharmaceuticals", Weight = 9.3, TrackingNumber = 670053128L }, - new Package { Company = "Wide World Importers", Weight = 33.8, TrackingNumber = 4665518773L } }; + List packages = [ + new ("Coho Vineyard", 25.2, 89453312L ), + new ("Lucerne Publishing", 18.7, 89112755L ), + new ("Wingtip Toys", 6.0, 299456122L ), + new ("Contoso Pharmaceuticals", 9.3, 670053128L ), + new ("Wide World Importers", 33.8, 4665518773L ) ]; // Create a Lookup to organize the packages. Use the first character of Company as the key value. // Select Company appended to TrackingNumber for each element value in the ILookup object. @@ -37,13 +34,15 @@ public static void ILookupExample() ); // Iterate through each value in the ILookup and output the contents. - foreach (var packageGroup in packageLookup) + foreach (IGrouping packageGroup in packageLookup) { // Print the key value. Console.WriteLine(packageGroup.Key); // Iterate through each value in the collection. foreach (string str in packageGroup) + { Console.WriteLine(" {0}", str); + } } // This code produces the following output: diff --git a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj new file mode 100644 index 00000000000..b2438766608 --- /dev/null +++ b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/ILookup.csproj @@ -0,0 +1,9 @@ + + + + Library + net8.0 + enable + + + \ No newline at end of file diff --git a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/Project.csproj b/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/Project.csproj deleted file mode 100644 index c02dc5044e7..00000000000 --- a/snippets/csharp/System.Linq/ILookupTKey,TElement/Overview/Project.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Library - net6.0 - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.cs b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.cs index 404ecfd30fb..139217b6f53 100644 --- a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.cs +++ b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Linq; @@ -7,25 +6,25 @@ namespace IOrderedSequence { static class IOrderedSequence { - static void Main(string[] args) - { - Example2(); - } + static void Main() => Example2(); static void Example1() { // // Create an array of strings to sort. - string[] fruits = { "apricot", "orange", "banana", "mango", "apple", "grape", "strawberry" }; + string[] fruits = ["apricot", "orange", "banana", "mango", "apple", "grape", "strawberry"]; // Sort the strings first by their length and then alphabetically // by passing the identity selector function. IOrderedEnumerable sortedFruits1 = - fruits.OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit); + fruits.OrderBy(fruit => fruit.Length) + .ThenBy(fruit => fruit); // Output the resulting sequence of strings. foreach (string fruit in sortedFruits1) + { Console.WriteLine(fruit); + } // This code produces the following output: // @@ -46,7 +45,7 @@ static void Example2() { // // Create an array of strings to sort. - string[] fruits = { "apricot", "orange", "banana", "mango", "apple", "grape", "strawberry" }; + string[] fruits = ["apricot", "orange", "banana", "mango", "apple", "grape", "strawberry"]; // First sort the strings by their length. IOrderedEnumerable sortedFruits2 = fruits.OrderBy(fruit => fruit.Length); @@ -58,7 +57,9 @@ static void Example2() // Output the resulting sequence of strings. foreach (string fruit in sortedFruits3) + { Console.WriteLine(fruit); + } // This code produces the following output: // diff --git a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj new file mode 100644 index 00000000000..b2438766608 --- /dev/null +++ b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/IOrderedEnumerable.csproj @@ -0,0 +1,9 @@ + + + + Library + net8.0 + enable + + + \ No newline at end of file diff --git a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/Project.csproj b/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/Project.csproj deleted file mode 100644 index c02dc5044e7..00000000000 --- a/snippets/csharp/System.Linq/IOrderedEnumerableTElement/Overview/Project.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Library - net6.0 - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/Linq - Copy.txt b/snippets/csharp/System.Linq/Linq - Copy.txt new file mode 100644 index 00000000000..c6de5d07ea9 --- /dev/null +++ b/snippets/csharp/System.Linq/Linq - Copy.txt @@ -0,0 +1,61 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.11.35017.193 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AggregateTSource", "Queryable\AggregateTSource\AggregateTSource.csproj", "{DF972B67-A03E-4335-9C77-55B23CB2A61B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Comparers", "Enumerable\Comparers\Comparers.csproj", "{33FFC016-737E-458A-B934-51906302BD24}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Enumerable", "Enumerable\AggregateTSource\Enumerable.csproj", "{1FB32EED-539F-405D-A7E0-CB8886178B13}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IGrouping", "IGroupingTKey,TElement\Overview\IGrouping.csproj", "{272B9F43-D02D-4D44-BF4F-80118560CA4D}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ILookup", "ILookupTKey,TElement\Overview\ILookup.csproj", "{EFF5E75B-DC97-4973-9AA0-D17A7246D727}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IOrderedEnumerable", "IOrderedEnumerableTElement\Overview\IOrderedEnumerable.csproj", "{A0D8E2EB-8EBA-46F1-AC80-5D4F54F2B344}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{0AADD544-5364-466F-B46A-E3D0B8A25A0E}" + ProjectSection(SolutionItems) = preProject + ..\..\..\..\..\temp\.editorconfig = ..\..\..\..\..\temp\.editorconfig + ..\..\..\..\..\temp\.editorconfigMINE = ..\..\..\..\..\temp\.editorconfigMINE + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DF972B67-A03E-4335-9C77-55B23CB2A61B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DF972B67-A03E-4335-9C77-55B23CB2A61B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DF972B67-A03E-4335-9C77-55B23CB2A61B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DF972B67-A03E-4335-9C77-55B23CB2A61B}.Release|Any CPU.Build.0 = Release|Any CPU + {33FFC016-737E-458A-B934-51906302BD24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {33FFC016-737E-458A-B934-51906302BD24}.Debug|Any CPU.Build.0 = Debug|Any CPU + {33FFC016-737E-458A-B934-51906302BD24}.Release|Any CPU.ActiveCfg = Release|Any CPU + {33FFC016-737E-458A-B934-51906302BD24}.Release|Any CPU.Build.0 = Release|Any CPU + {1FB32EED-539F-405D-A7E0-CB8886178B13}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1FB32EED-539F-405D-A7E0-CB8886178B13}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1FB32EED-539F-405D-A7E0-CB8886178B13}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1FB32EED-539F-405D-A7E0-CB8886178B13}.Release|Any CPU.Build.0 = Release|Any CPU + {272B9F43-D02D-4D44-BF4F-80118560CA4D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {272B9F43-D02D-4D44-BF4F-80118560CA4D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {272B9F43-D02D-4D44-BF4F-80118560CA4D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {272B9F43-D02D-4D44-BF4F-80118560CA4D}.Release|Any CPU.Build.0 = Release|Any CPU + {EFF5E75B-DC97-4973-9AA0-D17A7246D727}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EFF5E75B-DC97-4973-9AA0-D17A7246D727}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EFF5E75B-DC97-4973-9AA0-D17A7246D727}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EFF5E75B-DC97-4973-9AA0-D17A7246D727}.Release|Any CPU.Build.0 = Release|Any CPU + {A0D8E2EB-8EBA-46F1-AC80-5D4F54F2B344}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A0D8E2EB-8EBA-46F1-AC80-5D4F54F2B344}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A0D8E2EB-8EBA-46F1-AC80-5D4F54F2B344}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A0D8E2EB-8EBA-46F1-AC80-5D4F54F2B344}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {1C179DD0-BF65-4A4C-89EF-7EAAE0A18CEE} + EndGlobalSection +EndGlobal diff --git a/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Project.csproj b/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Project.csproj deleted file mode 100644 index c02dc5044e7..00000000000 --- a/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Project.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Library - net6.0 - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj b/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj new file mode 100644 index 00000000000..030872b60a5 --- /dev/null +++ b/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj @@ -0,0 +1,9 @@ + + + + Library + net8.0 + enable + + + diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/Project.csproj b/snippets/csharp/System.Linq/Queryable/AggregateTSource/Project.csproj deleted file mode 100644 index c02dc5044e7..00000000000 --- a/snippets/csharp/System.Linq/Queryable/AggregateTSource/Project.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Library - net6.0 - - - \ No newline at end of file diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs b/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs index 9cdf0985ad1..d5ee5f634dd 100644 --- a/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs +++ b/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs @@ -4,10 +4,10 @@ namespace QueryableExamples { - public class Program + static class Program { // This part is just for testing the examples - static void Main(string[] args) + static void Main() { All.AllEx1(); All2.AllEx2(); @@ -17,7 +17,7 @@ static void Main(string[] args) static void AggregateEx1() { // - string sentence = "the quick brown fox jumps over the lazy dog"; + const string sentence = "the quick brown fox jumps over the lazy dog"; // Split the string into individual words. string[] words = sentence.Split(' '); @@ -25,7 +25,7 @@ static void AggregateEx1() // Use Aggregate() to prepend each word to the beginning of the // new sentence to reverse the word order. string reversed = - words.AsQueryable().Aggregate( + words.Aggregate( (workingSentence, next) => next + " " + workingSentence ); @@ -40,11 +40,11 @@ static void AggregateEx1() static void AggregateEx2() { // - int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 }; + int[] ints = [4, 8, 8, 3, 9, 0, 7, 8, 2]; // Count the even numbers in the array, using a seed value of 0. int numEven = - ints.AsQueryable().Aggregate( + ints.Aggregate( 0, (total, next) => next % 2 == 0 ? total + 1 : total ); @@ -60,16 +60,16 @@ static void AggregateEx2() static void AggregateEx3() { // - string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" }; + string[] fruits = ["apple", "mango", "orange", "passionfruit", "grape"]; // Determine whether any string in the array is longer than "banana". string longestName = - fruits.AsQueryable().Aggregate( - "banana", - (longest, next) => next.Length > longest.Length ? next : longest, - // Return the final result as an uppercase string. - fruit => fruit.ToUpper() - ); + fruits + .Aggregate( + "banana", + (longest, next) => next.Length > longest.Length ? next : longest, + // Return the final result as an uppercase string. + fruit => fruit.ToUpper()); Console.WriteLine( "The fruit with the longest name is {0}.", @@ -87,22 +87,23 @@ static void AggregateEx3() public static class All { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void AllEx1() { // Create an array of Pets. - Pet[] pets = { new Pet { Name="Barley", Age=10 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=6 } }; + Pet[] pets = [ + new ("Barley",10 ), + new ("Boots",4 ), + new ("Whiskers",6 ) ]; // Determine whether all pet names in the array start with 'B'. bool allStartWithB = - pets.AsQueryable().All(pet => pet.Name.StartsWith("B")); + pets.All(pet => pet.Name.StartsWith('B')); Console.WriteLine( "{0} pet names start with 'B'.", @@ -119,40 +120,39 @@ public static void AllEx1() static class All2 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } - class Person + class Person(string lastName, Pet[] pets) { - public string LastName { get; set; } - public Pet[] Pets { get; set; } + public string LastName { get; set; } = lastName; + public Pet[] Pets { get; set; } = pets; } public static void AllEx2() { - List people = new List - { new Person { LastName = "Haas", - Pets = new Pet[] { new Pet { Name="Barley", Age=10 }, - new Pet { Name="Boots", Age=14 }, - new Pet { Name="Whiskers", Age=6 }}}, - new Person { LastName = "Fakhouri", - Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}}, - new Person { LastName = "Antebi", - Pets = new Pet[] { new Pet { Name = "Belle", Age = 8} }}, - new Person { LastName = "Philips", - Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2}, - new Pet { Name = "Rover", Age = 13}} } - }; + List people = [ + new ("Haas", [ + new ("Barley",10 ), + new ("Boots",14 ), + new ("Whiskers",6 ) ]), + new ("Fakhouri", [ new ("Snowball", 1) ]), + new ("Antebi", [ new ("Belle", 8) ]), + new ("Philips", [ + new ("Sweetie", 2), + new ("Rover", 13) ] ) ]; // Determine which people have pets that are all older than 5. IEnumerable names = from person in people - where person.Pets.AsQueryable().All(pet => pet.Age > 5) + where person.Pets.All(pet => pet.Age > 5) select person.LastName; foreach (string name in names) + { Console.WriteLine(name); + } /* This code produces the following output: * @@ -165,15 +165,15 @@ where person.Pets.AsQueryable().All(pet => pet.Age > 5) #endregion #region Any - class Any1 + static class Any1 { public static void AnyEx1() { // - List numbers = new List { 1, 2 }; + List numbers = [1, 2]; // Determine if the list contains any elements. - bool hasElements = numbers.AsQueryable().Any(); + bool hasElements = numbers.Any(); // [CA1860] better to use "numbers.Count > 0;" ! Console.WriteLine("The list {0} empty.", hasElements ? "is not" : "is"); @@ -186,40 +186,40 @@ public static void AnyEx1() } // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } - class Person + class Person(string lastName, Pet[] pets) { - public string LastName { get; set; } - public Pet[] Pets { get; set; } + public string LastName { get; set; } = lastName; + public Pet[] Pets { get; set; } = pets; } public static void AnyEx2() { - List people = new List - { new Person { LastName = "Haas", - Pets = new Pet[] { new Pet { Name="Barley", Age=10 }, - new Pet { Name="Boots", Age=14 }, - new Pet { Name="Whiskers", Age=6 }}}, - new Person { LastName = "Fakhouri", - Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}}, - new Person { LastName = "Antebi", - Pets = new Pet[] { }}, - new Person { LastName = "Philips", - Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2}, - new Pet { Name = "Rover", Age = 13}} } - }; + List people = [ + new ("Haas", [ + new ("Barley",10 ), + new ("Boots",14 ), + new ("Whiskers",6 ) ]), + new ("Fakhouri", [ new ("Snowball", 1) ]), + new ("Antebi",[]), + new ("Philips", [ + new ("Sweetie", 2), + new ("Rover", 13) ] ) + ]; // Determine which people have a non-empty Pet array. IEnumerable names = from person in people - where person.Pets.AsQueryable().Any() + where person.Pets.Any() // [CA1860] better to use "where person.Pets.Length != 0" select person.LastName; foreach (string name in names) + { Console.WriteLine(name); + } /* This code produces the following output: @@ -230,28 +230,27 @@ where person.Pets.AsQueryable().Any() } // } - static class Any2 { // - class Pet + public class Pet(string name, int age, bool vaccinated) { - public string Name { get; set; } - public int Age { get; set; } - public bool Vaccinated { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; + public bool Vaccinated { get; set; } = vaccinated; } public static void AnyEx3() { // Create an array of Pet objects. - Pet[] pets = - { new Pet { Name="Barley", Age=8, Vaccinated=true }, - new Pet { Name="Boots", Age=4, Vaccinated=false }, - new Pet { Name="Whiskers", Age=1, Vaccinated=false } }; + Pet[] pets = [ + new ("Barley",8, true ), + new ("Boots",4, false ), + new ("Whiskers",1, false ) ]; // Determine whether any pets over age 1 are also unvaccinated. bool unvaccinated = - pets.AsQueryable().Any(p => p.Age > 1 && p.Vaccinated == false); + pets.Any(p => p.Age > 1 && !p.Vaccinated); Console.WriteLine( "There {0} unvaccinated animals over age one.", @@ -270,7 +269,7 @@ public static void AnyEx3() static void AsQueryableEx1() { // - List grades = new List { 78, 92, 100, 37, 81 }; + List grades = [78, 92, 100, 37, 81]; // Convert the List to an IQueryable. IQueryable iqueryable = grades.AsQueryable(); @@ -299,9 +298,9 @@ static void AsQueryableEx1() static void AverageEx1() { // - List grades = new List { 78, 92, 100, 37, 81 }; + List grades = [78, 92, 100, 37, 81]; - double average = grades.AsQueryable().Average(); + double average = grades.Average(); Console.WriteLine("The average grade is {0}.", average); @@ -315,9 +314,9 @@ static void AverageEx1() static void AverageEx2() { // - long?[] longs = { null, 10007L, 37L, 399846234235L }; + long?[] longs = [null, 10007L, 37L, 399846234235L]; - double? average = longs.AsQueryable().Average(); + double? average = longs.Average(); Console.WriteLine("The average is {0}.", average); @@ -331,10 +330,10 @@ static void AverageEx2() static void AverageEx3() { // - string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; + string[] fruits = ["apple", "banana", "mango", "orange", "passionfruit", "grape"]; // Determine the average string length in the array. - double average = fruits.AsQueryable().Average(s => s.Length); + double average = fruits.Average(s => s.Length); Console.WriteLine("The average string length is {0}.", average); @@ -351,19 +350,20 @@ static void AverageEx3() static void CastEx1() { // Get a list of the methods available on the String type. - List methods = typeof(String).GetMethods().ToList(); + List methods = [.. typeof(string).GetMethods()]; // Cast each MethodInfo object to a MemberInfo object. // Then select the names of those methods whose names // are less than 6 characters long. - IQueryable members = - methods.AsQueryable() + IQueryable members = methods.AsQueryable() .Cast() .Select(member => member.Name) .Where(name => name.Length < 6); foreach (string member in members) + { Console.WriteLine(member); + } /* This code produces the following output: @@ -387,18 +387,18 @@ static void CastEx2() // // Create a list of objects. - List words = - new List { "green", "blue", "violet" }; + List words = ["green", "blue", "violet"]; // Cast the objects in the list to type 'string' // and project the first letter of each string. - IEnumerable query = - words.AsQueryable() + var query = words .Cast() - .Select(str => str.Substring(0, 1)); + .Select(str => str[0]); - foreach (string s in query) + foreach (var s in query) + { Console.WriteLine(s); + } /* This code produces the following output: @@ -415,27 +415,29 @@ static void CastEx2() static class Concat { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } // This method creates and returns an array of Pet objects. static Pet[] GetCats() { - Pet[] cats = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] cats = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; return cats; } // This method creates and returns an array of Pet objects. static Pet[] GetDogs() { - Pet[] dogs = { new Pet { Name="Bounder", Age=3 }, - new Pet { Name="Snoopy", Age=14 }, - new Pet { Name="Fido", Age=9 } }; + Pet[] dogs = [ + new ("Bounder",3 ), + new ("Snoopy",14 ), + new ("Fido",9 ) ]; return dogs; } @@ -446,13 +448,14 @@ public static void ConcatEx1() // Concatenate a collection of cat names to a // collection of dog names by using Concat(). - IEnumerable query = - cats.AsQueryable() + IEnumerable query = cats .Select(cat => cat.Name) .Concat(dogs.Select(dog => dog.Name)); foreach (string name in query) + { Console.WriteLine(name); + } } // This code produces the following output: @@ -475,11 +478,14 @@ public static void ConcatEx2() // Concatenate a collection of cat names to a // collection of dog names by using SelectMany(). IEnumerable query = - new[] { cats.Select(cat => cat.Name), dogs.Select(dog => dog.Name) } - .AsQueryable().SelectMany(name => name); + new[] { cats.Select(cat => cat.Name), + dogs.Select(dog => dog.Name) } + .SelectMany(name => name); foreach (string name in query) + { Console.WriteLine(name); + } // This code produces the following output: // @@ -499,13 +505,13 @@ public static void ConcatEx2() static void ContainsEx1() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; // The string to search for in the array. - string mango = "mango"; + const string mango = "mango"; - bool hasMango = fruits.AsQueryable().Contains(mango); + bool hasMango = fruits.Contains(mango); Console.WriteLine( "The array {0} contain '{1}'.", @@ -524,10 +530,10 @@ static void ContainsEx1() static void CountEx1() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; - int numberOfFruits = fruits.AsQueryable().Count(); + int numberOfFruits = fruits.Count(); // [CA1829, RCS1077] better to use "fruits.Length;" Console.WriteLine( "There are {0} items in the array.", @@ -543,22 +549,23 @@ static void CountEx1() static class Count { // - class Pet + class Pet(string name, bool vaccinated) { - public string Name { get; set; } - public bool Vaccinated { get; set; } + public string Name { get; set; } = name; + public bool Vaccinated { get; set; } = vaccinated; } public static void CountEx2() { // Create an array of Pet objects. - Pet[] pets = { new Pet { Name="Barley", Vaccinated=true }, - new Pet { Name="Boots", Vaccinated=false }, - new Pet { Name="Whiskers", Vaccinated=false } }; + Pet[] pets = [ + new ("Barley", true ), + new ("Boots", false ), + new ("Whiskers", false ) ]; // Count the number of unvaccinated pets in the array. int numberUnvaccinated = - pets.AsQueryable().Count(p => p.Vaccinated == false); + pets.Count(p => !p.Vaccinated); Console.WriteLine( "There are {0} unvaccinated animals.", @@ -577,28 +584,26 @@ public static void CountEx2() static class DefaultIfEmpty1 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void DefaultIfEmptyEx1() { // Create a list of Pet objects. - List pets = - new List{ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + List pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; - // Call DefaultIfEmtpy() on the collection that Select() + // Call DefaultIfEmpty() on the collection that Select() // returns, so that if the initial list is empty, there // will always be at least one item in the returned array. - string[] names = - pets.AsQueryable() - .Select(pet => pet.Name) - .DefaultIfEmpty() - .ToArray(); + string[] names = [.. pets + .Select(pet => pet.Name) + .DefaultIfEmpty() ]; string first = names[0]; Console.WriteLine(first); @@ -615,31 +620,27 @@ public static void DefaultIfEmptyEx1a() { // // Create a list of Pet objects. - List pets = - new List{ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + List pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; // This query selects only those pets that are 10 or older. // In case there are no pets that meet that criteria, call // DefaultIfEmpty(). This code passes an (optional) default // value to DefaultIfEmpty(). - string[] oldPets = - pets.AsQueryable() - .Where(pet => pet.Age >= 10) - .Select(pet => pet.Name) - .DefaultIfEmpty("[EMPTY]") - .ToArray(); + string[] oldPets = [.. pets + .Where(pet => pet.Age >= 10) + .Select(pet => pet.Name) + .DefaultIfEmpty("[EMPTY]") ]; Console.WriteLine("First query: " + oldPets[0]); // This query selects only those pets that are 10 or older. // This code does not call DefaultIfEmpty(). - string[] oldPets2 = - pets.AsQueryable() - .Where(pet => pet.Age >= 10) - .Select(pet => pet.Name) - .ToArray(); + string[] oldPets2 = [.. pets + .Where(pet => pet.Age >= 10) + .Select(pet => pet.Name) ]; // There may be no elements in the array, so directly // accessing element 0 may throw an exception. @@ -647,7 +648,7 @@ public static void DefaultIfEmptyEx1a() { Console.WriteLine("Second query: " + oldPets2[0]); } - catch (Exception e) + catch (ApplicationException e) { Console.WriteLine("Second query: An exception was thrown: " + e.Message); } @@ -668,14 +669,16 @@ public static void DefaultIfEmptyEx1a() static void DistinctEx1() { // - List ages = new List { 21, 46, 46, 55, 17, 21, 55, 55 }; + List ages = [21, 46, 46, 55, 17, 21, 55, 55]; - IEnumerable distinctAges = ages.AsQueryable().Distinct(); + IEnumerable distinctAges = ages.Distinct(); Console.WriteLine("Distinct ages:"); foreach (int age in distinctAges) + { Console.WriteLine(age); + } /* This code produces the following output: @@ -695,14 +698,15 @@ static void DistinctEx1() static void ElementAtEx1() { // - string[] names = { "Hartono, Tommy", "Adams, Terry", + string[] names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; + "Hedlund, Magnus", "Ito, Shu" ]; - Random random = new Random(DateTime.Now.Millisecond); + Random random = new(DateTime.Now.Millisecond); string name = - names.AsQueryable().ElementAt(random.Next(0, names.Length)); + names.ElementAt(random.Next(0, names.Length)); + //names[random.Next(0, names.Length) ]; // simpler Console.WriteLine("The name chosen at random is '{0}'.", name); @@ -721,18 +725,18 @@ Yours may be different due to the use of Random. static void ElementAtOrDefaultEx1() { // - string[] names = { "Hartono, Tommy", "Adams, Terry", + string[] names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; + "Hedlund, Magnus", "Ito, Shu" ]; - int index = 20; + const int index = 20; - string name = names.AsQueryable().ElementAtOrDefault(index); + var name = names.ElementAtOrDefault(index); Console.WriteLine( "The name chosen at index {0} is '{1}'.", index, - String.IsNullOrEmpty(name) ? "[NONE AT THIS INDEX]" : name); + (name) ?? "[NONE AT THIS INDEX]"); /* This code produces the following output: @@ -748,16 +752,18 @@ The name chosen at index 20 is '[NONE AT THIS INDEX]'. static void ExceptEx1() { // - double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 }; - double[] numbers2 = { 2.2 }; + double[] numbers1 = [2.0, 2.1, 2.2, 2.3, 2.4, 2.5]; + double[] numbers2 = [2.2]; // Get the numbers from the first array that // are NOT in the second array. IEnumerable onlyInFirstSet = - numbers1.AsQueryable().Except(numbers2); + numbers1.Except(numbers2); foreach (double number in onlyInFirstSet) + { Console.WriteLine(number); + } /* This code produces the following output: @@ -777,10 +783,11 @@ static void ExceptEx1() static void FirstEx1() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 435, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 435, 67, 12, 19 ]; - int first = numbers.AsQueryable().First(); + int first = numbers.First(); + //int first = numbers[0]; // simpler Console.WriteLine(first); @@ -796,11 +803,11 @@ static void FirstEx1() static void FirstEx2() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 435, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 435, 67, 12, 19 ]; // Get the first number in the array that is greater than 80. - int first = numbers.AsQueryable().First(number => number > 80); + int first = numbers.First(number => number > 80); Console.WriteLine(first); @@ -819,10 +826,10 @@ static void FirstOrDefaultEx1() { // // Create an empty array. - int[] numbers = { }; + int[] numbers = []; // Get the first item in the array, or else the // default value for type int (0). - int first = numbers.AsQueryable().FirstOrDefault(); + int first = numbers.FirstOrDefault(); Console.WriteLine(first); @@ -838,27 +845,27 @@ static void FirstOrDefaultEx1() static void FirstOrDefaultEx2() { // - string[] names = { "Hartono, Tommy", "Adams, Terry", + string[] names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", - "Hedlund, Magnus", "Ito, Shu" }; + "Hedlund, Magnus", "Ito, Shu" ]; // Get the first string in the array that is longer // than 20 characters, or the default value for type // string (null) if none exists. - string firstLongName = - names.AsQueryable().FirstOrDefault(name => name.Length > 20); + var firstLongName = + names.FirstOrDefault(name => name.Length > 20); Console.WriteLine("The first long name is '{0}'.", firstLongName); // Get the first string in the array that is longer // than 30 characters, or the default value for type // string (null) if none exists. - string firstVeryLongName = - names.AsQueryable().FirstOrDefault(name => name.Length > 30); + var firstVeryLongName = + names.FirstOrDefault(name => name.Length > 30); Console.WriteLine( "There is {0} name that is longer than 30 characters.", - string.IsNullOrEmpty(firstVeryLongName) ? "NOT a" : "a"); + firstVeryLongName is null ? "NOT a" : "a"); /* This code produces the following output: @@ -873,10 +880,10 @@ There is NOT a name that is longer than 30 characters. static void FirstOrDefaultEx3() { // - List months = new List { }; + List months = []; // Setting the default value to 1 after the query. - int firstMonth1 = months.AsQueryable().FirstOrDefault(); + int firstMonth1 = months.FirstOrDefault(); if (firstMonth1 == 0) { firstMonth1 = 1; @@ -884,7 +891,7 @@ static void FirstOrDefaultEx3() Console.WriteLine("The value of the firstMonth1 variable is {0}", firstMonth1); // Setting the default value to 1 by using DefaultIfEmpty() in the query. - int firstMonth2 = months.AsQueryable().DefaultIfEmpty(1).First(); + int firstMonth2 = months.DefaultIfEmpty(1).First(); Console.WriteLine("The value of the firstMonth2 variable is {0}", firstMonth2); /* @@ -902,27 +909,28 @@ The value of the firstMonth2 variable is 1 static class GroupBy { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void GroupByEx1() { // Create a list of Pet objects. - List pets = - new List{ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 }, - new Pet { Name="Daisy", Age=4 } }; + List pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ), + new ("Daisy",4 ) ]; // Group the pets using Pet.Age as the key. // Use Pet.Name as the value for each entry. - var query = pets.AsQueryable().GroupBy(pet => pet.Age); + var query = pets + .GroupBy(pet => pet.Age); // Iterate over each IGrouping in the collection. - foreach (var ageGroup in query) + foreach (IGrouping ageGroup in query) { Console.WriteLine("Age group: {0} Number of pets: {1}", ageGroup.Key, ageGroup.Count()); } @@ -943,25 +951,25 @@ public static void GroupByEx1() static class GroupBy2 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void GroupByEx2() { // Create a list of Pet objects. - List pets = - new List{ new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 }, - new Pet { Name="Daisy", Age=4 } }; + List pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ), + new ("Daisy",4 ) ]; // Group the pets using Pet.Age as the key. // Use Pet.Name as the value for each entry. IEnumerable> query = - pets.AsQueryable().GroupBy(pet => pet.Age, pet => pet.Name); + pets.GroupBy(pet => pet.Age, pet => pet.Name); // Iterate over each IGrouping in the collection. foreach (IGrouping petGroup in query) @@ -971,7 +979,9 @@ public static void GroupByEx2() // Iterate over each value in the // IGrouping and print the value. foreach (string name in petGroup) + { Console.WriteLine(" {0}", name); + } } } @@ -994,26 +1004,26 @@ public static void GroupByEx2() static class GroupBy3 { // - class Pet + class Pet(string name, float age) { - public string Name { get; set; } - public double Age { get; set; } + public string Name { get; set; } = name; + public float Age { get; set; } = age; } public static void GroupByEx3() { // Create a list of pets. - List petsList = - new List{ new Pet { Name="Barley", Age=8.3 }, - new Pet { Name="Boots", Age=4.9 }, - new Pet { Name="Whiskers", Age=1.5 }, - new Pet { Name="Daisy", Age=4.3 } }; + List petsList = [ + new ("Barley",8.3f ), + new ("Boots",4.9f ), + new ("Whiskers",1.5f ), + new ("Daisy",4.3f ) ]; // Group Pet objects by the Math.Floor of their age. // Then project an anonymous type from each group // that consists of the key, the count of the group's // elements, and the minimum and maximum age in the group. - var query = petsList.AsQueryable().GroupBy( + var query = petsList.GroupBy( pet => Math.Floor(pet.Age), (age, pets) => new { @@ -1057,26 +1067,26 @@ public static void GroupByEx3() static class GroupBy4 { // - class Pet + class Pet(string name, float age) { - public string Name { get; set; } - public double Age { get; set; } + public string Name { get; set; } = name; + public float Age { get; set; } = age; } public static void GroupByEx4() { // Create a list of pets. - List petsList = - new List{ new Pet { Name="Barley", Age=8.3 }, - new Pet { Name="Boots", Age=4.9 }, - new Pet { Name="Whiskers", Age=1.5 }, - new Pet { Name="Daisy", Age=4.3 } }; + List petsList = [ + new ("Barley",8.3f ), + new ("Boots",4.9f ), + new ("Whiskers",1.5f ), + new ("Daisy",4.3f ) ]; // Group Pet.Age values by the Math.Floor of the age. // Then project an anonymous type from each group // that consists of the key, the count of the group's // elements, and the minimum and maximum age in the group. - var query = petsList.AsQueryable().GroupBy( + var query = petsList.GroupBy( pet => Math.Floor(pet.Age), pet => pet.Age, (baseAge, ages) => new @@ -1122,36 +1132,36 @@ public static void GroupByEx4() static class GroupJoin { // - class Person + class Person(string name) { - public string Name { get; set; } + public string Name { get; set; } = name; } - class Pet + class Pet(string name, Person owner) { - public string Name { get; set; } - public Person Owner { get; set; } + public string Name { get; set; } = name; + public Person Owner { get; set; } = owner; } public static void GroupJoinEx1() { - Person magnus = new Person { Name = "Hedlund, Magnus" }; - Person terry = new Person { Name = "Adams, Terry" }; - Person charlotte = new Person { Name = "Weiss, Charlotte" }; + Person magnus = new("Hedlund, Magnus"); + Person terry = new("Adams, Terry"); + Person charlotte = new("Weiss, Charlotte"); - Pet barley = new Pet { Name = "Barley", Owner = terry }; - Pet boots = new Pet { Name = "Boots", Owner = terry }; - Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; + Pet barley = new("Barley", terry); + Pet boots = new("Boots", terry); + Pet whiskers = new("Whiskers", charlotte); + Pet daisy = new("Daisy", magnus); - List people = new List { magnus, terry, charlotte }; - List pets = new List { barley, boots, whiskers, daisy }; + List people = [magnus, terry, charlotte]; + List pets = [barley, boots, whiskers, daisy]; // Create a list where each element is an anonymous // type that contains a person's name and a collection // of names of the pets that are owned by them. var query = - people.AsQueryable().GroupJoin(pets, + people.GroupJoin(pets, person => person, pet => pet.Owner, (person, petCollection) => @@ -1167,7 +1177,9 @@ public static void GroupJoinEx1() Console.WriteLine("{0}:", obj.OwnerName); // Output each of the owner's pet's names. foreach (string pet in obj.Pets) + { Console.WriteLine(" {0}", pet); + } } } @@ -1191,14 +1203,16 @@ public static void GroupJoinEx1() static void IntersectEx1() { // - int[] id1 = { 44, 26, 92, 30, 71, 38 }; - int[] id2 = { 39, 59, 83, 47, 26, 4, 30 }; + int[] id1 = [44, 26, 92, 30, 71, 38]; + int[] id2 = [39, 59, 83, 47, 26, 4, 30]; // Get the numbers that occur in both arrays (id1 and id2). - IEnumerable both = id1.AsQueryable().Intersect(id2); + IEnumerable both = id1.Intersect(id2); foreach (int id in both) + { Console.WriteLine(id); + } /* This code produces the following output: @@ -1215,36 +1229,36 @@ static void IntersectEx1() static class Join { // - class Person + class Person(string name) { - public string Name { get; set; } + public string Name { get; set; } = name; } - class Pet + class Pet(string name, Person owner) { - public string Name { get; set; } - public Person Owner { get; set; } + public string Name { get; set; } = name; + public Person Owner { get; set; } = owner; } public static void JoinEx1() { - Person magnus = new Person { Name = "Hedlund, Magnus" }; - Person terry = new Person { Name = "Adams, Terry" }; - Person charlotte = new Person { Name = "Weiss, Charlotte" }; + Person magnus = new("Hedlund, Magnus"); + Person terry = new("Adams, Terry"); + Person charlotte = new("Weiss, Charlotte"); - Pet barley = new Pet { Name = "Barley", Owner = terry }; - Pet boots = new Pet { Name = "Boots", Owner = terry }; - Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; - Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; + Pet barley = new("Barley", terry); + Pet boots = new("Boots", terry); + Pet whiskers = new("Whiskers", charlotte); + Pet daisy = new("Daisy", magnus); - List people = new List { magnus, terry, charlotte }; - List pets = new List { barley, boots, whiskers, daisy }; + List people = [magnus, terry, charlotte]; + List pets = [barley, boots, whiskers, daisy]; // Join the list of Person objects and the list of Pet objects // to create a list of person-pet pairs where each element is // an anonymous type that contains the name of pet and the name // of the person that owns the pet. - var query = people.AsQueryable().Join(pets, + var query = people.Join(pets, person => person, pet => pet.Owner, (person, pet) => @@ -1276,10 +1290,11 @@ public static void JoinEx1() static void LastEx1() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 67, 12, 19 ]; - int last = numbers.AsQueryable().Last(); + int last = numbers.Last(); + //int last = numbers[^1]; // simpler Console.WriteLine(last); @@ -1295,11 +1310,11 @@ static void LastEx1() static void LastEx2() { // - int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, - 83, 23, 87, 67, 12, 19 }; + int[] numbers = [ 9, 34, 65, 92, 87, 435, 3, 54, + 83, 23, 87, 67, 12, 19 ]; // Get the last number in the array that is greater than 80. - int last = numbers.AsQueryable().Last(num => num > 80); + int last = numbers.Last(num => num > 80); Console.WriteLine(last); @@ -1318,14 +1333,14 @@ static void LastOrDefaultEx1() { // // Create an empty array. - string[] fruits = { }; + string[] fruits = []; // Get the last item in the array, or else the default // value for type string (null). - string last = fruits.AsQueryable().LastOrDefault(); + var last = fruits.LastOrDefault(); Console.WriteLine( - String.IsNullOrEmpty(last) ? "[STRING IS NULL OR EMPTY]" : last); + last ?? "[STRING IS NULL OR EMPTY]"); /* This code produces the following output: @@ -1339,19 +1354,21 @@ [STRING IS NULL OR EMPTY] static void LastOrDefaultEx2() { // - double[] numbers = { 49.6, 52.3, 51.0, 49.4, 50.2, 48.3 }; + double[] numbers = [49.6, 52.3, 51.0, 49.4, 50.2, 48.3]; // Get the last number in the array that rounds to 50.0, // or else the default value for type double (0.0). double last50 = - numbers.AsQueryable().LastOrDefault(n => Math.Round(n) == 50.0); + numbers + .LastOrDefault(n => Math.Round(n) == 50.0); Console.WriteLine("The last number that rounds to 50 is {0}.", last50); // Get the last number in the array that rounds to 40.0, // or else the default value for type double (0.0). double last40 = - numbers.AsQueryable().LastOrDefault(n => Math.Round(n) == 40.0); + numbers + .LastOrDefault(n => Math.Round(n) == 40.0); Console.WriteLine( "The last number that rounds to 40 is {0}.", @@ -1370,10 +1387,10 @@ The last number that rounds to 40 is [DOES NOT EXIST]. static void LastOrDefaultEx3() { // - List daysOfMonth = new List { }; + List daysOfMonth = []; // Setting the default value to 1 after the query. - int lastDay1 = daysOfMonth.AsQueryable().LastOrDefault(); + int lastDay1 = daysOfMonth.LastOrDefault(); if (lastDay1 == 0) { lastDay1 = 1; @@ -1381,7 +1398,7 @@ static void LastOrDefaultEx3() Console.WriteLine("The value of the lastDay1 variable is {0}", lastDay1); // Setting the default value to 1 by using DefaultIfEmpty() in the query. - int lastDay2 = daysOfMonth.AsQueryable().DefaultIfEmpty(1).Last(); + int lastDay2 = daysOfMonth.DefaultIfEmpty(1).Last(); Console.WriteLine("The value of the lastDay2 variable is {0}", lastDay2); /* @@ -1398,10 +1415,10 @@ The value of the lastDay2 variable is 1 public static void LongCountEx1() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; - long count = fruits.AsQueryable().LongCount(); + long count = fruits.LongCount(); // [CA1829] better to use "fruits.Length;" Console.WriteLine("There are {0} fruits in the collection.", count); @@ -1417,22 +1434,24 @@ There are 6 fruits in the collection. static class LongCount { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void LongCountEx2() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; const int Age = 3; // Count the number of Pet objects where Pet.Age is greater than 3. - long count = pets.AsQueryable().LongCount(pet => pet.Age > Age); + long count = pets + .LongCount(pet => pet.Age > Age); Console.WriteLine("There are {0} animals over age {1}.", count, Age); } @@ -1451,9 +1470,9 @@ There are 2 animals over age 3. static void MaxEx1() { // - List longs = new List { 4294967296L, 466855135L, 81125L }; + List longs = [4294967296L, 466855135L, 81125L]; - long max = longs.AsQueryable().Max(); + var max = longs.Max(); Console.WriteLine("The largest number is {0}.", max); @@ -1469,22 +1488,22 @@ The largest number is 4294967296. static class Max2 // with a selector { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void MaxEx2() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; // Add Pet.Age to the length of Pet.Name // to determine the "maximum" Pet object in the array. - int max = - pets.AsQueryable().Max(pet => pet.Age + pet.Name.Length); + var max = pets.Max(pet => pet.Age + pet.Name.Length); Console.WriteLine( "The maximum pet age plus name length is {0}.", @@ -1506,9 +1525,9 @@ The maximum pet age plus name length is 14. static void MinEx1() { // - double[] doubles = { 1.5E+104, 9E+103, -2E+103 }; + double[] doubles = [1.5E+104, 9E+103, -2E+103]; - double min = doubles.AsQueryable().Min(); + var min = doubles.Min(); Console.WriteLine("The smallest number is {0}.", min); @@ -1524,20 +1543,21 @@ The smallest number is -2E+103. static class Min2 // with a selector { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void MinEx2() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; // Get the Pet object that has the smallest Age value. - int min = pets.AsQueryable().Min(pet => pet.Age); + var min = pets.Min(pet => pet.Age); Console.WriteLine("The youngest animal is age {0}.", min); } @@ -1557,15 +1577,17 @@ static void OfTypeEx1() { // // Create a list of MemberInfo objects. - List members = typeof(String).GetMembers().ToList(); + List members = [.. typeof(string).GetMembers()]; // Return only those items that can be cast to type PropertyInfo. - IQueryable propertiesOnly = - members.AsQueryable().OfType(); + var propertiesOnly = + members.OfType(); Console.WriteLine("Members of type 'PropertyInfo' are:"); foreach (System.Reflection.PropertyInfo pi in propertiesOnly) + { Console.WriteLine(pi.Name); + } /* This code produces the following output: @@ -1583,24 +1605,26 @@ static void OfTypeEx1() static class OrderBy { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void OrderByEx1() { - Pet[] pets = { new Pet { Name="Barley", Age=8 }, - new Pet { Name="Boots", Age=4 }, - new Pet { Name="Whiskers", Age=1 } }; + Pet[] pets = [ + new ("Barley",8 ), + new ("Boots",4 ), + new ("Whiskers",1 ) ]; // Sort the Pet objects in the array by Pet.Age. - IEnumerable query = - pets.AsQueryable().OrderBy(pet => pet.Age); + IEnumerable query = pets.OrderBy(pet => pet.Age); foreach (Pet pet in query) + { Console.WriteLine("{0} - {1}", pet.Name, pet.Age); + } } /* @@ -1658,28 +1682,28 @@ public int Compare(decimal d1, decimal d2) fractional2 = d2; } - if (fractional1 == fractional2) - return Decimal.Compare(d1, d2); - else if (fractional1 > fractional2) - return 1; - else - return -1; + return fractional1 == fractional2 + ? decimal.Compare(d1, d2) + : fractional1 > fractional2 + ? 1 : -1; } } public static void OrderByDescendingEx1() { List decimals = - new List { 6.2m, 8.3m, 0.5m, 1.3m, 6.3m, 9.7m }; + [6.2m, 8.3m, 0.5m, 1.3m, 6.3m, 9.7m]; // Sort the decimal values in descending order // by using a custom comparer. IEnumerable query = - decimals.AsQueryable() + decimals .OrderByDescending(num => num, new SpecialComparer()); foreach (decimal num in query) + { Console.WriteLine(num); + } } /* @@ -1701,13 +1725,16 @@ public static void OrderByDescendingEx1() static void ReverseEx1() { // - char[] apple = { 'a', 'p', 'p', 'l', 'e' }; + char[] apple = ['a', 'p', 'p', 'l', 'e']; // Reverse the order of the characters in the collection. - IQueryable reversed = apple.AsQueryable().Reverse(); + var reversed = apple.Reverse(); foreach (char chr in reversed) + { Console.Write(chr + " "); + } + Console.WriteLine(); /* @@ -1725,14 +1752,16 @@ static void SelectEx1() { // List range = - new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Project the square of each int value. IEnumerable squares = - range.AsQueryable().Select(x => x * x); + range.Select(x => x * x); foreach (int num in squares) + { Console.WriteLine(num); + } /* This code produces the following output: @@ -1755,20 +1784,21 @@ static void SelectEx1() static void SelectEx2() { // - string[] fruits = { "apple", "banana", "mango", "orange", - "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", "orange", + "passionfruit", "grape" ]; // Project an anonymous type that contains the // index of the string in the source array, and // a string that contains the same number of characters // as the string's index in the source array. - var query = - fruits.AsQueryable() + var query = fruits .Select((fruit, index) => - new { index, str = fruit.Substring(0, index) }); + new { index, str = fruit[..index] }); foreach (var obj in query) + { Console.WriteLine("{0}", obj); + } /* This code produces the following output: @@ -1789,42 +1819,46 @@ static void SelectEx2() static class SelectMany1 { // - class PetOwner + class PetOwner(string name, List pets) { - public string Name { get; set; } - public List Pets { get; set; } + public string Name { get; set; } = name; + public List Pets { get; set; } = pets; } public static void SelectManyEx1() { - PetOwner[] petOwners = - { new PetOwner { Name="Higa, Sidney", - Pets = new List{ "Scruffy", "Sam" } }, - new PetOwner { Name="Ashkenazi, Ronen", - Pets = new List{ "Walker", "Sugar" } }, - new PetOwner { Name="Price, Vernette", - Pets = new List{ "Scratches", "Diesel" } } }; + PetOwner[] petOwners = [ + new ("Higa, Sidney", + ["Scruffy", "Sam"] ), + new ("Ashkenazi, Ronen", + ["Walker", "Sugar"] ), + new ("Price, Vernette", + ["Scratches", "Diesel"] ) ]; // Query using SelectMany(). IEnumerable query1 = - petOwners.AsQueryable().SelectMany(petOwner => petOwner.Pets); + petOwners + .SelectMany(petOwner => petOwner.Pets); Console.WriteLine("Using SelectMany():"); // Only one foreach loop is required to iterate through the // results because it is a one-dimensional collection. foreach (string pet in query1) + { Console.WriteLine(pet); + } // This code shows how to use Select() instead of SelectMany(). - IEnumerable> query2 = - petOwners.AsQueryable().Select(petOwner => petOwner.Pets); + IEnumerable> query2 = + petOwners + .Select(petOwner => petOwner.Pets); Console.WriteLine("\nUsing Select():"); // Notice that two foreach loops are required to iterate through // the results because the query returns a collection of arrays. - foreach (List petList in query2) + foreach (List petList in query2) { foreach (string pet in petList) { @@ -1862,36 +1896,37 @@ Using Select(): static class SelectMany2 { // - class PetOwner + class PetOwner(string name, List pets) { - public string Name { get; set; } - public List Pets { get; set; } + public string Name { get; set; } = name; + public List Pets { get; set; } = pets; } public static void SelectManyEx2() { - PetOwner[] petOwners = - { new PetOwner { Name="Higa, Sidney", - Pets = new List{ "Scruffy", "Sam" } }, - new PetOwner { Name="Ashkenazi, Ronen", - Pets = new List{ "Walker", "Sugar" } }, - new PetOwner { Name="Price, Vernette", - Pets = new List{ "Scratches", "Diesel" } }, - new PetOwner { Name="Hines, Patrick", - Pets = new List{ "Dusty" } } }; + PetOwner[] petOwners = [ + new ("Higa, Sidney", + ["Scruffy", "Sam"] ), + new ("Ashkenazi, Ronen", + ["Walker", "Sugar"] ), + new ("Price, Vernette", + ["Scratches", "Diesel"] ), + new ("Hines, Patrick", + ["Dusty"] ) ]; // For each PetOwner element in the source array, // project a sequence of strings where each string // consists of the index of the PetOwner element in the // source array and the name of each pet in PetOwner.Pets. - IEnumerable query = - petOwners.AsQueryable() + IEnumerable query = petOwners .SelectMany( - (petOwner, index) => petOwner.Pets.Select(pet => index + pet) + (petOwner, index) => petOwner.Pets.Select(pet => index + pet) ); foreach (string pet in query) + { Console.WriteLine(pet); + } } // This code produces the following output: @@ -1910,47 +1945,41 @@ public static void SelectManyEx2() static class SelectMany3 { // - class PetOwner + class PetOwner(string name, List pets) { - public string Name { get; set; } - public List Pets { get; set; } + public string Name { get; set; } = name; + public List Pets { get; set; } = pets; } - class Pet + class Pet(string name, string breed) { - public string Name { get; set; } - public string Breed { get; set; } + public string Name { get; set; } = name; + public string Breed { get; set; } = breed; } public static void SelectManyEx3() { - PetOwner[] petOwners = - { new PetOwner { Name="Higa", - Pets = new List{ - new Pet { Name="Scruffy", Breed="Poodle" }, - new Pet { Name="Sam", Breed="Hound" } } }, - new PetOwner { Name="Ashkenazi", - Pets = new List{ - new Pet { Name="Walker", Breed="Collie" }, - new Pet { Name="Sugar", Breed="Poodle" } } }, - new PetOwner { Name="Price", - Pets = new List{ - new Pet { Name="Scratches", Breed="Dachshund" }, - new Pet { Name="Diesel", Breed="Collie" } } }, - new PetOwner { Name="Hines", - Pets = new List{ - new Pet { Name="Dusty", Breed="Collie" } } } - }; + PetOwner[] petOwners = [ + new ("Higa", [ + new ("Scruffy","Poodle" ), + new ("Sam","Hound" ) ] ), + new ("Ashkenazi", [ + new ("Walker","Collie" ), + new ("Sugar","Poodle" ) ] ), + new ("Price", [ + new ("Scratches","Dachshund" ), + new ("Diesel","Collie" ) ] ), + new ("Hines", [new ("Dusty","Collie" ) ] ) + ]; // This query demonstrates how to obtain a sequence of // the names of all the pets whose breed is "Collie", while // keeping an association with the owner that owns the pet. - var query = - petOwners.AsQueryable() - // Create a sequence of ALL the Pet objects. Then - // project an anonymous type that consists of each - // Pet in the new sequence and the PetOwner object - // from the initial array that corresponds to that pet. + var query = petOwners + // Create a sequence of ALL the Pet objects. Then + // project an anonymous type that consists of each + // Pet in the new sequence and the PetOwner object + // from the initial array that corresponds to that pet. .SelectMany(owner => owner.Pets, (owner, pet) => new { owner, pet }) // Filter the sequence of anonymous types to only @@ -1966,7 +1995,9 @@ public static void SelectManyEx3() // Print the results. foreach (var obj in query) + { Console.WriteLine(obj); + } } /* This code produces the following output: @@ -1984,23 +2015,23 @@ public static void SelectManyEx3() static class SequenceEqual1 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void SequenceEqualEx1() { - Pet pet1 = new Pet { Name = "Turbo", Age = 2 }; - Pet pet2 = new Pet { Name = "Peanut", Age = 8 }; + Pet pet1 = new("Turbo", 2); + Pet pet2 = new("Peanut", 8); // Create two lists of pets. - List pets1 = new List { pet1, pet2 }; - List pets2 = new List { pet1, pet2 }; + List pets1 = [pet1, pet2]; + List pets2 = [pet1, pet2]; // Determine if the lists are equal. - bool equal = pets1.AsQueryable().SequenceEqual(pets2); + bool equal = pets1.SequenceEqual(pets2); Console.WriteLine( "The lists {0} equal.", @@ -2019,26 +2050,25 @@ The lists are equal. static class SequenceEqual2 { // - class Pet + class Pet(string name, int age) { - public string Name { get; set; } - public int Age { get; set; } + public string Name { get; set; } = name; + public int Age { get; set; } = age; } public static void SequenceEqualEx2() { - Pet pet1 = new Pet() { Name = "Turbo", Age = 2 }; - Pet pet2 = new Pet() { Name = "Peanut", Age = 8 }; + Pet pet1 = new("Turbo", 2); + Pet pet2 = new("Peanut", 8); // Create two lists of pets. - List pets1 = new List { pet1, pet2 }; - List pets2 = new List { - new Pet { Name = "Turbo", Age = 2 }, - new Pet { Name = "Peanut", Age = 8 } - }; + List pets1 = [pet1, pet2]; + List pets2 = [ + new ("Turbo", 2 ), + new ("Peanut", 8 ) ]; // Determine if the lists are equal. - bool equal = pets1.AsQueryable().SequenceEqual(pets2); + bool equal = pets1.SequenceEqual(pets2); Console.WriteLine("The lists {0} equal.", equal ? "are" : "are NOT"); } @@ -2058,18 +2088,18 @@ static void SingleEx1() { // // Create two arrays. - string[] fruits1 = { "orange" }; - string[] fruits2 = { "orange", "apple" }; + string[] fruits1 = ["orange"]; + string[] fruits2 = ["orange", "apple"]; // Get the only item in the first array. - string fruit1 = fruits1.AsQueryable().Single(); + string fruit1 = fruits1.Single(); Console.WriteLine("First query: " + fruit1); try { // Try to get the only item in the second array. - string fruit2 = fruits2.AsQueryable().Single(); + string fruit2 = fruits2.Single(); Console.WriteLine("Second query: " + fruit2); } catch (System.InvalidOperationException) @@ -2095,11 +2125,12 @@ static void SingleEx1() static void SingleEx2() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; // Get the only string in the array whose length is greater than 10. - string fruit1 = fruits.AsQueryable().Single(fruit => fruit.Length > 10); + string fruit1 = fruits + .Single(fruit => fruit.Length > 10); Console.WriteLine("First Query: " + fruit1); @@ -2107,7 +2138,8 @@ static void SingleEx2() { // Try to get the only string in the array // whose length is greater than 15. - string fruit2 = fruits.AsQueryable().Single(fruit => fruit.Length > 15); + string fruit2 = fruits + .Single(fruit => fruit.Length > 15); Console.WriteLine("Second Query: " + fruit2); } catch (System.InvalidOperationException) @@ -2133,19 +2165,18 @@ static void SingleOrDefaultEx1() { // // Create two arrays. The second is empty. - string[] fruits1 = { "orange" }; - string[] fruits2 = { }; + string[] fruits1 = ["orange"]; + string[] fruits2 = []; // Get the only item in the first array, or else // the default value for type string (null). - string fruit1 = fruits1.AsQueryable().SingleOrDefault(); + var fruit1 = fruits1.SingleOrDefault(); Console.WriteLine("First Query: " + fruit1); // Get the only item in the second array, or else // the default value for type string (null). - string fruit2 = fruits2.AsQueryable().SingleOrDefault(); - Console.WriteLine("Second Query: " + - (String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2)); + var fruit2 = fruits2.SingleOrDefault(); + Console.WriteLine("Second Query: " + fruit2 ?? "No such string!"); /* This code produces the following output: @@ -2160,21 +2191,21 @@ static void SingleOrDefaultEx1() static void SingleOrDefaultEx2() { // - string[] fruits = { "apple", "banana", "mango", - "orange", "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", + "orange", "passionfruit", "grape" ]; // Get the single string in the array whose length is greater // than 10, or else the default value for type string (null). - string fruit1 = - fruits.AsQueryable().SingleOrDefault(fruit => fruit.Length > 10); + var fruit1 = fruits + .SingleOrDefault(fruit => fruit.Length > 10); Console.WriteLine("First Query: " + fruit1); // Get the single string in the array whose length is greater // than 15, or else the default value for type string (null). - string fruit2 = - fruits.AsQueryable().SingleOrDefault(fruit => fruit.Length > 15); + var fruit2 = fruits + .SingleOrDefault(fruit => fruit.Length > 15); Console.WriteLine("Second Query: " + - (String.IsNullOrEmpty(fruit2) ? "No such string!" : fruit2)); + fruit2 ?? "No such string!"); /* This code produces the following output: @@ -2189,10 +2220,10 @@ static void SingleOrDefaultEx2() static void SingleOrDefaultEx3() { // - int[] pageNumbers = { }; + int[] pageNumbers = []; // Setting the default value to 1 after the query. - int pageNumber1 = pageNumbers.AsQueryable().SingleOrDefault(); + int pageNumber1 = pageNumbers.SingleOrDefault(); if (pageNumber1 == 0) { pageNumber1 = 1; @@ -2200,7 +2231,7 @@ static void SingleOrDefaultEx3() Console.WriteLine("The value of the pageNumber1 variable is {0}", pageNumber1); // Setting the default value to 1 by using DefaultIfEmpty() in the query. - int pageNumber2 = pageNumbers.AsQueryable().DefaultIfEmpty(1).Single(); + int pageNumber2 = pageNumbers.DefaultIfEmpty(1).Single(); Console.WriteLine("The value of the pageNumber2 variable is {0}", pageNumber2); /* @@ -2218,16 +2249,18 @@ The value of the pageNumber2 variable is 1 static void SkipEx1() { // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; // Sort the grades in descending order and // get all except the first three. - IEnumerable lowerGrades = - grades.AsQueryable().OrderByDescending(g => g).Skip(3); + IEnumerable lowerGrades = grades + .OrderByDescending(g => g).Skip(3); Console.WriteLine("All grades except the top three are:"); foreach (int grade in lowerGrades) + { Console.WriteLine(grade); + } /* This code produces the following output: @@ -2247,20 +2280,22 @@ static void SkipEx1() static void SkipWhileEx1() { // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; // Get all grades less than 80 by first // sorting the grades in descending order and then // taking all the grades after the first grade // that is less than 80. IEnumerable lowerGrades = - grades.AsQueryable() + grades .OrderByDescending(grade => grade) .SkipWhile(grade => grade >= 80); Console.WriteLine("All grades below 80:"); foreach (int grade in lowerGrades) + { Console.WriteLine(grade); + } /* This code produces the following output: @@ -2277,18 +2312,19 @@ static void SkipWhileEx1() static void SkipWhileEx2() { // - int[] amounts = { 5000, 2500, 9000, 8000, - 6500, 4000, 1500, 5500 }; + int[] amounts = [ 5000, 2500, 9000, 8000, + 6500, 4000, 1500, 5500 ]; // Skip over amounts in the array until the first amount // that is less than or equal to the product of its // index in the array and 1000. Take the remaining items. - IEnumerable query = - amounts.AsQueryable() + IEnumerable query = amounts .SkipWhile((amount, index) => amount > index * 1000); foreach (int amount in query) + { Console.WriteLine(amount); + } /* This code produces the following output: @@ -2306,9 +2342,9 @@ static void SkipWhileEx2() static void SumEx1() { // - List numbers = new List { 43.68F, 1.25F, 583.7F, 6.5F }; + List numbers = [43.68F, 1.25F, 583.7F, 6.5F]; - float sum = numbers.AsQueryable().Sum(); + float sum = numbers.Sum(); Console.WriteLine("The sum of the numbers is {0}.", sum); @@ -2324,9 +2360,9 @@ The sum of the numbers is 635.13. static void SumEx2() { // - float?[] points = { null, 0, 92.83F, null, 100.0F, 37.46F, 81.1F }; + float?[] points = [null, 0, 92.83F, null, 100.0F, 37.46F, 81.1F]; - float? sum = points.AsQueryable().Sum(); + float? sum = points.Sum(); Console.WriteLine("Total points earned: {0}", sum); @@ -2342,23 +2378,23 @@ static void SumEx2() static class Sum3 { // - class Package + class Package(string company, double weight) { - public string Company { get; set; } - public double Weight { get; set; } + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; } public static void SumEx3() { - List packages = - new List - { new Package { Company = "Coho Vineyard", Weight = 25.2 }, - new Package { Company = "Lucerne Publishing", Weight = 18.7 }, - new Package { Company = "Wingtip Toys", Weight = 6.0 }, - new Package { Company = "Adventure Works", Weight = 33.8 } }; + List packages = [ + new ("Coho Vineyard", 25.2 ), + new ("Lucerne Publishing", 18.7 ), + new ("Wingtip Toys", 6.0 ), + new ("Adventure Works", 33.8 ) ]; // Calculate the sum of all package weights. - double totalWeight = packages.AsQueryable().Sum(pkg => pkg.Weight); + double totalWeight = packages + .Sum(pkg => pkg.Weight); Console.WriteLine("The total weight of the packages is: {0}", totalWeight); } @@ -2377,15 +2413,17 @@ public static void SumEx3() static void TakeEx1() { // - int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; + int[] grades = [59, 82, 70, 56, 92, 98, 85]; // Sort the grades in descending order and take the first three. - IEnumerable topThreeGrades = - grades.AsQueryable().OrderByDescending(grade => grade).Take(3); + IEnumerable topThreeGrades = grades + .OrderByDescending(grade => grade).Take(3); Console.WriteLine("The top three grades are:"); foreach (int grade in topThreeGrades) + { Console.WriteLine(grade); + } /* This code produces the following output: @@ -2404,17 +2442,18 @@ static void TakeEx1() static void TakeWhileEx1() { // - string[] fruits = { "apple", "banana", "mango", "orange", - "passionfruit", "grape" }; + string[] fruits = [ "apple", "banana", "mango", "orange", + "passionfruit", "grape" ]; // Take strings from the array until a string // that is equal to "orange" is found. - IEnumerable query = - fruits.AsQueryable() - .TakeWhile(fruit => String.Compare("orange", fruit, true) != 0); + IEnumerable query = fruits + .TakeWhile(fruit => string.Compare("orange", fruit, true) != 0); foreach (string fruit in query) + { Console.WriteLine(fruit); + } /* This code produces the following output: @@ -2430,17 +2469,18 @@ static void TakeWhileEx1() static void TakeWhileEx2() { // - string[] fruits = { "apple", "passionfruit", "banana", "mango", - "orange", "blueberry", "grape", "strawberry" }; + string[] fruits = [ "apple", "passionfruit", "banana", "mango", + "orange", "blueberry", "grape", "strawberry" ]; // Take strings from the array until a string whose length // is less than its index in the array is found. - IEnumerable query = - fruits.AsQueryable() + IEnumerable query = fruits .TakeWhile((fruit, index) => fruit.Length >= index); foreach (string fruit in query) + { Console.WriteLine(fruit); + } /* This code produces the following output: @@ -2461,17 +2501,19 @@ static void TakeWhileEx2() static void ThenByEx1() { // - string[] fruits = { "grape", "passionfruit", "banana", "apple", - "orange", "raspberry", "mango", "blueberry" }; + string[] fruits = [ "grape", "passionfruit", "banana", "apple", + "orange", "raspberry", "mango", "blueberry" ]; // Sort the strings first by their length and then // alphabetically by passing the identity selector function. - IEnumerable query = - fruits.AsQueryable() - .OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit); + IEnumerable query = fruits + .OrderBy(fruit => fruit.Length) + .ThenBy(fruit => fruit); foreach (string fruit in query) + { Console.WriteLine(fruit); + } /* This code produces the following output: @@ -2494,28 +2536,21 @@ static void ThenByEx1() static class ThenByDescending { // - public class CaseInsensitiveComparer : IComparer - { - public int Compare(string x, string y) - { - return string.Compare(x, y, true); - } - } - public static void ThenByDescendingEx1() { string[] fruits = - { "apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE" }; + ["apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE"]; // Sort the strings first ascending by their length and // then descending using a custom case insensitive comparer. - IEnumerable query = - fruits.AsQueryable() + IEnumerable query = fruits .OrderBy(fruit => fruit.Length) - .ThenByDescending(fruit => fruit, new CaseInsensitiveComparer()); + .ThenByDescending(fruit => fruit, StringComparer.OrdinalIgnoreCase); foreach (string fruit in query) + { Console.WriteLine(fruit); + } } /* @@ -2539,14 +2574,16 @@ public static void ThenByDescendingEx1() static void UnionEx1() { // - int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 }; - int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 }; + int[] ints1 = [5, 3, 9, 7, 5, 9, 3, 7]; + int[] ints2 = [8, 3, 6, 4, 4, 9, 1, 0]; // Get the set union of the items in the two arrays. - IEnumerable union = ints1.AsQueryable().Union(ints2); + IEnumerable union = ints1.Union(ints2); foreach (int num in union) + { Console.Write("{0} ", num); + } /* This code produces the following output: @@ -2564,16 +2601,17 @@ 5 3 9 7 8 6 4 1 0 static void WhereEx1() { // - List fruits = - new List { "apple", "passionfruit", "banana", "mango", - "orange", "blueberry", "grape", "strawberry" }; + List fruits = [ "apple", "passionfruit", "banana", "mango", + "orange", "blueberry", "grape", "strawberry" ]; // Get all strings whose length is less than 6. - IEnumerable query = - fruits.AsQueryable().Where(fruit => fruit.Length < 6); + IEnumerable query = fruits + .Where(fruit => fruit.Length < 6); foreach (string fruit in query) + { Console.WriteLine(fruit); + } /* This code produces the following output: @@ -2589,16 +2627,17 @@ static void WhereEx1() static void WhereEx2() { // - int[] numbers = { 0, 30, 20, 15, 90, 85, 40, 75 }; + int[] numbers = [0, 30, 20, 15, 90, 85, 40, 75]; // Get all the numbers that are less than or equal to // the product of their index in the array and 10. - IEnumerable query = - numbers.AsQueryable() + IEnumerable query = numbers .Where((number, index) => number <= index * 10); foreach (int number in query) + { Console.WriteLine(number); + } /* This code produces the following output: @@ -2617,13 +2656,16 @@ static void WhereEx2() static void ZipEx() { // - int[] numbers = { 1, 2, 3, 4 }; - string[] words = { "one", "two", "three" }; + int[] numbers = [1, 2, 3, 4]; + string[] words = ["one", "two", "three"]; - var numbersAndWords = numbers.AsQueryable().Zip(words, (first, second) => first + " " + second); + var numbersAndWords = numbers + .Zip(words, (first, second) => first + " " + second); - foreach (var item in numbersAndWords) + foreach (string item in numbersAndWords) + { Console.WriteLine(item); + } // This code produces the following output: diff --git a/snippets/csharp/System.Linq/README.txt b/snippets/csharp/System.Linq/README.txt new file mode 100644 index 00000000000..f992bcd2ae3 --- /dev/null +++ b/snippets/csharp/System.Linq/README.txt @@ -0,0 +1,9 @@ +1. the LINQ docs C# samples [in GitHub repo] consist of 6 projects to showcase IEnumerable and IQueryable +unfortunately much code unecessarily invokes AsQueryable despite simpler IEnumerable method implementations existing +- [thus such guidance is poor as such AsQueryable () can be avoided] +2. should update to useful modern C# v12 semantics [Primary constructors, Collection expressions, Span, is, etc] +3. calls made to default parameterless ctor then assigning individual properties, rather than using parameterised ctors explicitly +- or better yet primary constructor +4. current analyzers also disclose numerous Warnings/Messages, emphasising poor guidance for today's coding +5. many cases of wastefully using Any(),Count(),LongCount etc when optimal coding available (e.g. Count, Length for Collections). +6. spurious ToString() call in OrderByIComparer() [line #1804] From 7525ed13e4690ea020c3cf684b25271100759772 Mon Sep 17 00:00:00 2001 From: DickBaker Date: Tue, 16 Jul 2024 16:21:39 +0100 Subject: [PATCH 8/8] resolve missing project (fix "Run snippets 5000 for PR" step) --- .../Overview/Lookup.csproj | 8 +++++++ .../LookupTKey,TElement/Overview/lookup.cs | 24 +++++++++---------- ...gregateTSource.csproj => Queryable.csproj} | 0 .../Queryable/AggregateTSource/queryable.cs | 2 +- 4 files changed, 20 insertions(+), 14 deletions(-) create mode 100644 snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Lookup.csproj rename snippets/csharp/System.Linq/Queryable/AggregateTSource/{AggregateTSource.csproj => Queryable.csproj} (100%) diff --git a/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Lookup.csproj b/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Lookup.csproj new file mode 100644 index 00000000000..5a1b02db677 --- /dev/null +++ b/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Lookup.csproj @@ -0,0 +1,8 @@ + + + + Library + net8.0 + + + \ No newline at end of file diff --git a/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/lookup.cs b/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/lookup.cs index 20dd79e95f1..9700948ebc1 100644 --- a/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/lookup.cs +++ b/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/lookup.cs @@ -7,27 +7,25 @@ namespace SequenceExamples { static class IGrouping { - static void Main(string[] args) - { - LookupExample(); - } + static void Main() => LookupExample(); // - class Package + class Package(string company, double weight, long trackingNumber) { - public string Company; - public double Weight; - public long TrackingNumber; + public string Company { get; set; } = company; + public double Weight { get; set; } = weight; + public long TrackingNumber { get; set; } = trackingNumber; } public static void LookupExample() { // Create a list of Packages to put into a Lookup data structure. - List packages = new List { new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L }, - new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L }, - new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L }, - new Package { Company = "Contoso Pharmaceuticals", Weight = 9.3, TrackingNumber = 670053128L }, - new Package { Company = "Wide World Importers", Weight = 33.8, TrackingNumber = 4665518773L } }; + List packages = [ + new("Coho Vineyard", 25.2, 89453312L ), + new("Lucerne Publishing", 18.7, 89112755L ), + new("Wingtip Toys", 6.0, 299456122L ), + new("Contoso Pharmaceuticals", 9.3, 670053128L ), + new("Wide World Importers", 33.8, 4665518773L ) ]; // Create a Lookup to organize the packages. Use the first character of Company as the key value. // Select Company appended to TrackingNumber for each element value in the Lookup. diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj b/snippets/csharp/System.Linq/Queryable/AggregateTSource/Queryable.csproj similarity index 100% rename from snippets/csharp/System.Linq/Queryable/AggregateTSource/AggregateTSource.csproj rename to snippets/csharp/System.Linq/Queryable/AggregateTSource/Queryable.csproj diff --git a/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs b/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs index d5ee5f634dd..6112bc46d4b 100644 --- a/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs +++ b/snippets/csharp/System.Linq/Queryable/AggregateTSource/queryable.cs @@ -1418,7 +1418,7 @@ public static void LongCountEx1() string[] fruits = [ "apple", "banana", "mango", "orange", "passionfruit", "grape" ]; - long count = fruits.LongCount(); // [CA1829] better to use "fruits.Length;" + long count = fruits.LongCount(); // [CA1829, RCS1077] better to use "fruits.Length;" Console.WriteLine("There are {0} fruits in the collection.", count);