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/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/IGroupingTKey,TElement/Overview/Project.csproj b/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Lookup.csproj similarity index 72% rename from snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/Project.csproj rename to snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Lookup.csproj index c02dc5044e7..5a1b02db677 100644 --- a/snippets/csharp/System.Linq/IGroupingTKey,TElement/Overview/Project.csproj +++ b/snippets/csharp/System.Linq/LookupTKey,TElement/Overview/Lookup.csproj @@ -2,7 +2,7 @@ Library - net6.0 + net8.0 \ No newline at end of file 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/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/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.csproj b/snippets/csharp/System.Linq/Queryable/AggregateTSource/Queryable.csproj new file mode 100644 index 00000000000..030872b60a5 --- /dev/null +++ b/snippets/csharp/System.Linq/Queryable/AggregateTSource/Queryable.csproj @@ -0,0 +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 9cdf0985ad1..6112bc46d4b 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, RCS1077] 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]