C#例子01-LINQ方法操作-Sum求和

发布时间:2017-12-15 浏览次数:7313 次
C#例子01-LINQ方法操作-Sum求和

以下例子展示如何用LINQ的聚集方法的定义可枚举类

Sum (LINQ)
enumerable.sum是system.linq命名空间的扩展方法。它返回集合中的数值的总和。
1 计算数据类型
比如获取整数列表的求和
var numbers =new List<int> { 8, 2, 6, 3 };
int sum = numbers.Sum();// sum: 19
统计decimal 类型的列表的总数
var numbers =new List<decimal> { 8.1m, 2.2m, 6.1m, 3.3m };
decimal sum = numbers.Sum(); // sum: 19.7
如果在空集合中调用Sum方法,则返回0
var numbers =new List<int>();// empty list
int sum = numbers.Sum();// sum: 0
2 可空整数类型的求和
求一个int?的列表的总和
var numbers = new List<int?> { 8, 2, null, 3 };
int? sum = numbers.Sum();  // sum: 13
如果集合中包含的只是null元素则返回0
var numbers = new List<int?> { null };
int? sum = numbers.Sum();  // sum: 0
如果一个元素都没有 则也返回0
var numbers = new List<int?>();  // empty list
int? sum = numbers.Sum();        // sum: 0
3 带有条件的Sum运算
下面例子是计算所有字符串的长度,使用sum
var stringList = new List<string> { "北盟网校", "22", "666666", "www.bamn.cn" };
//下面两行其实是一样效果
int lengthSum = stringList.Select(x => x.Length).Sum();  // lengthSum: 19
int lengthSum = stringList.Sum(x => x.Length);           // lengthSum: 19

4 带有查询语法的Sum运算
在集合中使用linq的query表达式去对整数列表进行求和
var list = new List<int> { 8, 2, 6, 3 };
int sum = (from x in list select x).Sum();  // sum: 19
当然可以在Linq的QUERY表达式中带上条件
比如
var list = new List<int> { 8, 2, 6, 3 };
int sum = (from x in list where x > 4 select x).Sum();  // sum: 14
使用select的query表达式去得到字符串的长度总数
var list = new List<string> { "88888888", "22", "666666", "333" };
int lengthSum = (from x in list select x.Length).Sum();  // lengthSum: 19

5 sum中使用group by
下面例子讲解如何使用sum来统计每一组比如下面 每一个player属于一个组team的然后又一个得分score 然后我们使用sum来统计分组中所有玩家的分数
var players = new List<Player> {
    new Player { Name = "Alex", Team = "A", Score = 10 },
    new Player { Name = "Anna", Team = "A", Score = 20 },
    new Player { Name = "Luke", Team = "L", Score = 60 },
    new Player { Name = "Lucy", Team = "L", Score = 40 },
};

var teamTotalScores =
    from player in players
    group player by player.Team into playerGroup
    select new
    {
        Team = playerGroup.Key,
        TotalScore = playerGroup.Sum(x => x.Score),
    };

// teamTotalScores is 是一个匿名对象是集合
// { Team = "A", TotalScore = 30 }
// { Team = "L", TotalScore = 100 }

当然我们可以封装一些扩展方法来计算集合中的和
public static int Sum(this IEnumerable<int> source)
{
    if (source == null) throw Error.ArgumentNull("source");
    int sum = 0;
    checked {
        foreach (int v in source) sum += v;
    }
    return sum;
}
可空类型集合
public static int? Sum(this IEnumerable<int?> source)
{
    if (source == null) throw Error.ArgumentNull("source");
    int sum = 0;
    checked {
        foreach (int? v in source) {
            if (v != null) sum += v.GetValueOrDefault();
        }
    }
    return sum;
}