78 lines
2.4 KiB
C#
Raw Normal View History

using System;
2021-07-05 18:21:52 +10:00
using System.Collections.Generic;
using System.Diagnostics;
2021-07-15 16:56:14 +10:00
using System.Linq;
2021-07-05 18:21:52 +10:00
using automatically_implemented_properties;
namespace automatically_implemented_properties
{
class Program
{
static void Main(string[] args)
{
2021-07-15 16:56:14 +10:00
Product[] products =
{
2021-07-15 16:56:14 +10:00
new Product {Name = "Kayak", Category = "Watersports", Price = 275M},
new Product {Name = "Lifejacket", Category = "Watersports", Price = 48.95M},
new Product {Name = "Soccer ball", Category = "Soccer", Price = 19.50M},
new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M}
2021-07-05 18:21:52 +10:00
};
2021-07-15 16:56:14 +10:00
// define the array to hold results
Product[] results = new Product[3];
// sort the contents of the array
Array.Sort(products, (item1, item2) =>
{
2021-07-15 16:56:14 +10:00
return Comparer<decimal>.Default.Compare(item1.Price, item2.Price);
});
// get the first three items in the array as the results
Array.Copy(products, results, 3);
// print out the name
foreach (Product p in results)
{
Console.WriteLine("Item: {0}, Cost: {1}", p.Name, p.Price);
}
2021-07-15 16:56:14 +10:00
int count = 0;
// print the name
}
}
2021-07-05 18:21:52 +10:00
public static class MyExtensionMethod
{
public static decimal TotalPrices(this IEnumerable<Product> productEnum)
{
2021-07-05 18:21:52 +10:00
decimal total = 0;
foreach (Product prod in productEnum)
2021-07-05 18:21:52 +10:00
{
total += prod.Price;
}
return total;
}
public static IEnumerable<Product> FilterByCategory(this IEnumerable<Product> productEnum,
string categoryParam)
{
foreach (Product prod in productEnum)
{
if (prod.Category == categoryParam)
{
yield return prod;
}
}
}
public static IEnumerable<Product> Filter(this IEnumerable<Product> productEnum,
Func<Product, bool> selectorParam)
{
foreach (Product prod in productEnum)
{
if (selectorParam(prod))
{
yield return prod;
}
}
}
}
}