e.g. 5.27 Using LINQ to Query Data

chap5
Jason Zhu 2021-07-15 17:00:53 +10:00
parent e2aa8c7cba
commit bf4a437acd
1 changed files with 16 additions and 15 deletions

View File

@ -18,23 +18,24 @@ namespace automatically_implemented_properties
new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M} new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M}
}; };
// define the array to hold results var results = from product in products
Product[] results = new Product[3]; orderby product.Price descending
// sort the contents of the array select new
Array.Sort(products, (item1, item2) =>
{ {
return Comparer<decimal>.Default.Compare(item1.Price, item2.Price); product.Name,
}); product.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);
}
int count = 0; int count = 0;
// print the name // print out the names
foreach (var p in results)
{
Console.WriteLine("Item: {0}, Cost: {1}", p.Name, p.Price);
if (++count == 3)
{
break;
}
}
} }
} }