【C# .NET】LINQ With EF Core

settings.xml



  
  
  

linq 扩展

using System.Collections.Generic;

namespace System.Linq // extend Microsoft’s namespace
{
  public static class MyLinqExtensions
  {
    // this is a chainable LINQ extension method 
    public static IEnumerable ProcessSequence(
      this IEnumerable sequence)
    {
      // you could do some processing here
      return sequence;
    }

    // these are scalar LINQ extension methods
    public static int? Median(this IEnumerable sequence)
    {
      var ordered = sequence.OrderBy(item => item); 
      int middlePosition = ordered.Count() / 2; 
      return ordered.ElementAt(middlePosition);
    }

    public static int? Median(
      this IEnumerable sequence, Func selector)
    {
      return sequence.Select(selector).Median();
    }

    public static decimal? Median(this IEnumerable sequence)
    {
      var ordered = sequence.OrderBy(item => item); 
      int middlePosition = ordered.Count() / 2; 
      return ordered.ElementAt(middlePosition);
    }

    public static decimal? Median(
      this IEnumerable sequence, Func selector)
    {
      return sequence.Select(selector).Median();
    }

    public static int? Mode(this IEnumerable sequence)
    {
      var grouped = sequence.GroupBy(item => item);
      var orderedGroups = grouped.OrderByDescending(group => group.Count());
      return orderedGroups.FirstOrDefault().Key;
    }

    public static int? Mode(
      this IEnumerable sequence, Func selector)
    {
      return sequence.Select(selector).Mode();
    }

    public static decimal? Mode(this IEnumerable sequence)
    {
      var grouped = sequence.GroupBy(item => item);
      var orderedGroups = grouped.OrderByDescending(group => group.Count());
      return orderedGroups.FirstOrDefault().Key;
    }

    public static decimal? Mode(
      this IEnumerable sequence, Func selector)
    {
      return sequence.Select(selector).Mode();
    }
  }
}

示例

using System;
using static System.Console;
using Packt.Shared;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Xml.Linq;

namespace LinqWithEFCore
{
    class Program
    {
        /*
         Products that cost less than $10:
         41: Jack's New England Clam Chowder costs $9.65
         45: Rogede sild costs $9.50
         47: Zaanse koeken costs $9.50
         19: Teatime Chocolate Biscuits costs $9.20
         23: Tunnbr?d costs $9.00
         75: Rh?nbr?u Klosterbier costs $7.75
         54: Tourtière costs $7.45
         52: Filo Mix costs $7.00
         13: Konbu costs $6.00
         24: Guaraná Fantástica costs $4.50
         33: Geitost costs $2.50
          */
        static void FilterAndSort()
        {
            using (var db = new Northwind())
            {
                var query = db.Products
                  // query is a DbSet
                  .ProcessSequence()
                  .Where(product => product.UnitPrice < 10M)
                  // query is now an IQueryable
                  .OrderByDescending(product => product.UnitPrice)
                  // query is now an IOrderedQueryable
                  .Select(product => new //匿名类型 anonymous type
                  {
                      product.ProductID,
                      product.ProductName,
                      product.UnitPrice
                  });

                WriteLine("Products that cost less than $10:");
                foreach (var item in query)
                {
                    WriteLine("{0}: {1} costs {2:$#,##0.00}",
                      item.ProductID, item.ProductName, item.UnitPrice);
                }
                WriteLine();
            }
        }

        static void JoinCategoriesAndProducts()
        {
            using (var db = new Northwind())
            {
                //将每个产品加入其类别以返回 77 个匹配项 join every product to its category to return 77 matches 
                var queryJoin = db.Categories.Join(
                  inner: db.Products,
                  outerKeySelector: category => category.CategoryID,
                  innerKeySelector: product => product.CategoryID,
                  resultSelector: (c, p) =>
                    new { c.CategoryName, p.ProductName, p.ProductID })
                  .OrderBy(cp => cp.CategoryName);

                foreach (var item in queryJoin)
                {
                    WriteLine("{0}: {1} is in {2}.",
                      arg0: item.ProductID,
                      arg1: item.ProductName,
                      arg2: item.CategoryName);
                }
            }
        }

        /*
         Beverages has 12 products.
            Chai
            Chang
            Guaraná Fantástica
            Sasquatch Ale
            Steeleye Stout
            C?te de Blaye
            Chartreuse verte
            Ipoh Coffee
            Laughing Lumberjack Lager
            Outback Lager
            Rh?nbr?u Klosterbier
            Lakkalik??ri
        Condiments has 12 products.
            Aniseed Syrup
            Chef Anton's Cajun Seasoning
            Chef Anton's Gumbo Mix
            Grandma's Boysenberry Spread
            Northwoods Cranberry Sauce
            Genen Shouyu
            Gula Malacca
            Sirop d'érable
            Vegie-spread
            Louisiana Fiery Hot Pepper Sauce
            Louisiana Hot Spiced Okra
            Original Frankfurter grüne So?e
        Confections has 13 products.
            Pavlova
            Teatime Chocolate Biscuits
            Sir Rodney's Marmalade
            Sir Rodney's Scones
            NuNuCa Nu?-Nougat-Creme
            Gumb?r Gummib?rchen
            Schoggi Schokolade
            Zaanse koeken
            Chocolade
            Maxilaku
            Valkoinen suklaa
            Tarte au sucre
            Scottish Longbreads
        Dairy Products has 10 products.
            Queso Cabrales
            Queso Manchego La Pastora
            Gorgonzola Telino
            Mascarpone Fabioli
            Geitost
            Raclette Courdavault
            Camembert Pierrot
            Gudbrandsdalsost
            Flotemysost
            Mozzarella di Giovanni
        Grains/Cereals has 7 products.
            Gustaf's Kn?ckebr?d
            Tunnbr?d
            Singaporean Hokkien Fried Mee
            Filo Mix
            Gnocchi di nonna Alice
            Ravioli Angelo
            Wimmers gute Semmelkn?del
        Meat/Poultry has 6 products.
            Mishi Kobe Niku
            Alice Mutton
            Thüringer Rostbratwurst
            Perth Pasties
            Tourtière
            Paté chinois
        Produce has 5 products.
            Uncle Bob's Organic Dried Pears
            Tofu
            R?ssle Sauerkraut
            Manjimup Dried Apples
            Longlife Tofu
        Seafood has 12 products.
            Ikura
            Konbu
            Carnarvon Tigers
            Nord-Ost Matjeshering
            Inlagd Sill
            Gravad lax
            Boston Crab Meat
            Jack's New England Clam Chowder
            Rogede sild
            Spegesild
            Escargots de Bourgogne
            R?d Kaviar
        */
        static void GroupJoinCategoriesAndProducts()
        {
            using (var db = new Northwind())
            {
                // group all products by their category to return 8 matches 
                var queryGroup = db.Categories.AsEnumerable().GroupJoin(
                  inner: db.Products,
                  outerKeySelector: category => category.CategoryID,
                  innerKeySelector: product => product.CategoryID,
                  resultSelector: (c, matchingProducts) => new
                  {
                      c.CategoryName,
                      Products = matchingProducts//.OrderBy(p => p.ProductName)
                  });

                foreach (var item in queryGroup)
                {
                    WriteLine("{0} has {1} products.",
                      arg0: item.CategoryName,
                      arg1: item.Products.Count());

                    foreach (var product in item.Products)
                    {
                        WriteLine($"  {product.ProductName}");
                    }
                }
            }
        }

        /*
        Product count:                    77
        Highest product price:       $263.50
        Sum of units in stock:         3,119
        Sum of units on order:           780
        Average unit price:           $28.87
        Value of units in stock:  $74,050.85
        */
        static void AggregateProducts() //聚合序列: 均值 求和 
        {
            using (var db = new Northwind())
            {
                WriteLine("{0,-25} {1,10}",
                  arg0: "Product count:",
                  arg1: db.Products.Count());

                WriteLine("{0,-25} {1,10:$#,##0.00}",
                  arg0: "Highest product price:",
                  arg1: db.Products.Max(p => p.UnitPrice));

                WriteLine("{0,-25} {1,10:N0}",
                  arg0: "Sum of units in stock:",
                  arg1: db.Products.Sum(p => p.UnitsInStock));

                WriteLine("{0,-25} {1,10:N0}",
                  arg0: "Sum of units on order:",
                  arg1: db.Products.Sum(p => p.UnitsOnOrder));

                WriteLine("{0,-25} {1,10:$#,##0.00}",
                  arg0: "Average unit price:",
                  arg1: db.Products.Average(p => p.UnitPrice));

                WriteLine("{0,-25} {1,10:$#,##0.00}",
                  arg0: "Value of units in stock:",
                  arg1: db.Products.AsEnumerable()
                    .Sum(p => p.UnitPrice * p.UnitsInStock));
            }
        }

        /*
        Mean units in stock: 41
        Mean unit price: $28.87
        Median units in stock: 26
        Median unit price: $19.50
        Mode units in stock: 0
        Mode unit price: $18.00
         */
        static void CustomExtensionMethods()
        {
            using (var db = new Northwind())
            {
                WriteLine("Mean units in stock: {0:N0}",
                  db.Products.Average(p => p.UnitsInStock));

                WriteLine("Mean unit price: {0:$#,##0.00}",
                  db.Products.Average(p => p.UnitPrice));

                WriteLine("Median units in stock: {0:N0}",
                  db.Products.Median(p => p.UnitsInStock));

                WriteLine("Median unit price: {0:$#,##0.00}",
                  db.Products.Median(p => p.UnitPrice));

                WriteLine("Mode units in stock: {0:N0}",//库存模式单位
                  db.Products.Mode(p => p.UnitsInStock));

                WriteLine("Mode unit price: {0:$#,##0.00}",
                  db.Products.Mode(p => p.UnitPrice));
            }
        }

        /*
         
          
            Chai
          
          
            Chang
          
          
            Aniseed Syrup
          
          
            Chef Anton's Cajun Seasoning
          
          
            Chef Anton's Gumbo Mix
          
          
            Grandma's Boysenberry Spread
          
          
            Uncle Bob's Organic Dried Pears
          
          
            Northwoods Cranberry Sauce
          
          
            Mishi Kobe Niku
          
          
            Ikura
          
          
            Queso Cabrales
          
          
            Queso Manchego La Pastora
          
          
            Konbu
          
          
            Tofu
          
          
            Genen Shouyu
          
          
            Pavlova
          
          
            Alice Mutton
          
          
            Carnarvon Tigers
          
          
            Teatime Chocolate Biscuits
          
          
            Sir Rodney's Marmalade
          
          
            Sir Rodney's Scones
          
          
            Gustaf's Kn?ckebr?d
          
          
            Tunnbr?d
          
          
            Guaraná Fantástica
          
          
            NuNuCa Nu?-Nougat-Creme
          
          
            Gumb?r Gummib?rchen
          
          
            Schoggi Schokolade
          
          
            R?ssle Sauerkraut
          
          
            Thüringer Rostbratwurst
          
          
            Nord-Ost Matjeshering
          
          
            Gorgonzola Telino
          
          
            Mascarpone Fabioli
          
          
            Geitost
          
          
            Sasquatch Ale
          
          
            Steeleye Stout
          
          
            Inlagd Sill
          
          
            Gravad lax
          
          
            C?te de Blaye
          
          
            Chartreuse verte
          
          
            Boston Crab Meat
          
          
            Jack's New England Clam Chowder
          
          
            Singaporean Hokkien Fried Mee
          
          
            Ipoh Coffee
          
          
            Gula Malacca
          
          
            Rogede sild
          
          
            Spegesild
          
          
            Zaanse koeken
          
          
            Chocolade
          
          
            Maxilaku
          
          
            Valkoinen suklaa
          
          
            Manjimup Dried Apples
          
          
            Filo Mix
          
          
            Perth Pasties
          
          
            Tourtière
          
          
            Paté chinois
          
          
            Gnocchi di nonna Alice
          
          
            Ravioli Angelo
          
          
            Escargots de Bourgogne
          
          
            Raclette Courdavault
          
          
            Camembert Pierrot
          
          
            Sirop d'érable
          
          
            Tarte au sucre
          
          
            Vegie-spread
          
          
            Wimmers gute Semmelkn?del
          
          
            Louisiana Fiery Hot Pepper Sauce
          
          
            Louisiana Hot Spiced Okra
          
          
            Laughing Lumberjack Lager
          
          
            Scottish Longbreads
          
          
            Gudbrandsdalsost
          
          
            Outback Lager
          
          
            Flotemysost
          
          
            Mozzarella di Giovanni
          
          
            R?d Kaviar
          
          
            Longlife Tofu
          
          
            Rh?nbr?u Klosterbier
          
          
            Lakkalik??ri
          
          
            Original Frankfurter grüne So?e
          
        
         */
        static void OutputProductsAsXml()//输出数组为xml格式
        {
            using (var db = new Northwind())
            {
                var productsForXml = db.Products.ToArray();

                var xml = new XElement("products",
                  from p in productsForXml
                  select new XElement("product",
                    new XAttribute("id", p.ProductID),
                    new XAttribute("price", p.UnitPrice),
                    new XElement("name", p.ProductName)));

                WriteLine(xml.ToString());
            }
        }

        //xml设置
        /*
        color: red
        size: large
        price: 23.99
         */
        static void ProcessSettings()
        {
            XDocument doc = XDocument.Load("settings.xml");
            //Descendants 按文档顺序返回此文档或元素的后代元素的过滤集合。 集合中仅包含具有匹配 System.Xml.Linq.XName 的元素。
            var appSettings = doc.Descendants("appSettings")
              .Descendants("add")
              .Select(node => new
              {
                  Key = node.Attribute("key").Value,
                  Value = node.Attribute("value").Value
              }).ToArray();

            foreach (var item in appSettings)
            {
                WriteLine($"{item.Key}: {item.Value}");
            }
        }

        static void Main(string[] args)
        {
            //FilterAndSort();

            // JoinCategoriesAndProducts();

            // GroupJoinCategoriesAndProducts();
            // AggregateProducts();
            // CustomExtensionMethods();
            // OutputProductsAsXml();
            ProcessSettings();
            ReadLine();
        }
    }
}

你可能感兴趣的:(linq,c#,.net)