Linq学习笔记--聚合函数/Aggregator

以下代码均来自微软官网


///


/// 去掉重复项之后,获得个数
///

public void Linq1()
{
    int[] factorsOf300 = { 2, 2, 3, 5, 5 };

    int uniqueFactors = factorsOf300.Distinct().Count();

    Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors);
}

---结果  3

///


/// 带有Lambda表达式的、
/// 获得所有的奇数的个数
///

public void Linq2()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    int oddNumbers = numbers.Count(n => n % 2 == 1);

    Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);
}

---结果  5

///


/// 带有Lambda表达式的、
/// 获得所有的奇数的个数
///

public void Linq3()
{
    List products = GetProductList();  //获得一个集合、
GetProductList()代码省略....

    var categoryCounts =
        from p in products
        group p by p.Category into g                   //按每个对象的"分类"进行分组,并给每个组起名为g(个人理解..)
        select new { Category = g.Key, ProductCount = g.Count() };
}

///


/// 求和
///

public void Linq4()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    double numSum = numbers.Sum();

    Console.WriteLine("The sum of the numbers is {0}.", numSum);
}

---结果       The sum of the numbers is 45.

///


/// 求:所有字母长度的和
///

public void Linq5()
{
    string[] words = { "cherry", "apple", "blueberry" };

    double totalChars = words.Sum(w => w.Length);

    Console.WriteLine("There are a total of {0} characters in these words.", totalChars);
}

---结果    There are a total of 20 characters in these words.

///


/// 求最小值
///

public void Linq6()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    int minNum = numbers.Min();

    Console.WriteLine("The minimum number is {0}.", minNum);
}

---结果   The minimum number is 0.


///


/// 求最短的单词长度
///

public void Linq7()
{
    string[] words = { "cherry", "apple", "blueberry" };

    int shortestWord = words.Min(w => w.Length);

    Console.WriteLine("The shortest word is {0} characters long.", shortestWord);
}

---结果   The shortest word is 5 characters long.

///


/// 求大值
///

public void Linq8()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    int maxNum = numbers.Max();

    Console.WriteLine("The maximum number is {0}.", maxNum);
}

---结果  The maximum number is 9.

///


/// 求平均数
///

public void Linq9()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    double averageNum = numbers.Average();

    Console.WriteLine("The average number is {0}.", averageNum);
}

---结果      The average number is 4.5.

===============================华丽的分割线===============================

///


/// 累计求乘积
///

public void Linq10()
{
    double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };

    //累计的一个循环相乘的过程,返回最后相乘后的结果
    double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);

    Console.WriteLine("Total product of all numbers: {0}", product);
}

---结果  Total product of all numbers: 88.33081

///


/// 我也不知道这个例子是到底要干什么.可能只是为了讲述语法吧...
///

public void Linq11()
{
    double startBalance = 100.0;

    int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 };

    //乍一看有些复杂,让人找不着北,其实慢慢细看,其实也就是Lambda里嵌套一个Lambda,
    //我们可以把代码拆分为AAAA()  :下面....
 
    double endBalance =
        attemptedWithdrawals.Aggregate(startBalance,
            (balance, nextWithdrawal) =>
                ((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance));

    Console.WriteLine("Ending balance: {0}", endBalance);
}


///


/// 这是上面拆分来的代码~
///

public void AAAA()
{
     double startBalance = 100.0;

     int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 };

     double endBalance =
         attemptedWithdrawals.Aggregate(startBalance,(balance, nextWithdrawal) =>aaa(balance,nextWithdrawal));

     Console.WriteLine("Ending balance: {0}", endBalance);
}


double aaa(double a, double b)
{
     return (b <= a) ? (a - b) : a;
}

---结果  DE>Ending balance: 20DE>

///


/// let关键字的用法。传统的子查询看起来始终有些不太直观
/// 两种写法效果一样,并且let更加直观
/// (个人感觉就像一个给子查询的别名)
///

public void Linq12()
{
    int[] numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
   
//传统下的子查询做法 
    var query = from num in numbers
        select num * (from n in numbers  where n % 2 == 0  select n).Count();

    //使用LET关键字的做法 
    //var query = from num in numbers
    //let evenNumbers = from n in numbers
//给查询出来的能整除2的数字一个"名字"
    //where n % 2 == 0
    //select n 
    //select num * evenNumbers.Count();

    foreach (var item in query)
    {
         Console.WriteLine(item);
    }
}

---结果
4
8
12
16
20
24
28
32
36

你可能感兴趣的:(C#,LINQ)