对List<>中的相同元素求和

时间:2014-05-10 17:02:09

标签: c# entity-framework

c#/ entityFramework有一些初学者的问题...显示的表格更大,我不知道'姓名'表格中的价值......

我有一个像这样的表tblFruits:

**tblFruits     
ID  Name    Amount (kg)**
1   apple   10
2   orange  20
3   orange  30
4   lemon   40
5   apple   50
6   orange  60

我希望只展示一次相同的水果并总结相同水果的数量。

这是输出:

**tblFruitsTotal        
ID  Name    Amount(kg)**
1   apple   60
2   orange  110
3   lemon   40

我需要一个List对象来绑定它我的数据网格在xaml..whats中最好的方法吗?请帮忙

3 个答案:

答案 0 :(得分:1)

试试这个......

public class Fruit
    {

        public int Quantity { get; set; }
        public string Name { get; set; }
    }

    static void Main(string[] args)
        {

            var fruits = new List<Fruit>
            {
                new Fruit {Name = "Apple", Quantity = 10},
                new Fruit {Name = "Orange", Quantity = 20},
                new Fruit {Name = "Orange", Quantity = 60},
                new Fruit {Name = "Apple", Quantity = 50}
            };


            var groupedFruit = fruits.GroupBy(l => l.Name)
                          .Select(lg =>
                                new
                                {
                                    Name = lg.Key,
                                    TotalQuantity = lg.Sum(q => q.Quantity)
                                });

            foreach (var fruit in groupedFruit)
            {
                Console.WriteLine("Fruit: {0} : Quantity: {1}", 
                    fruit.Name, fruit.TotalQuantity);
            }

            Console.Read();
        }

我已将代码添加到控制台应用程序中,以便您了解其工作原理。

答案 1 :(得分:0)

foreach (Fruits item in tblFruits.GroupBy(x => x.Name))
{
    tblFruitsTotal.Add(new Fruits() 
    { 
        ID = tblFruitsTotal.Any() ? tblFruitsTotal.Max(x=>x.ID) + 1 : 1,
        Name = item.First().Name, 
        Amount = item.Sum(x => x.Amount) 
    });
}

请务必加入'using System.Linq;'

答案 2 :(得分:-2)

下面将说明所有值,使它们唯一并增加数量。

Dictionary<string, value> _newTable = new Dictionary<string, value>();
foreach (var fruit in tblFruits) {
    if (!_newTable.contains(fruit.name)) {
        _newTable.Add(fruit.name, 0);
    }

    _newTable[fruit.name] += fruit.amount;
}

这是documentation,它是可枚举的和集合。列表也是如此,应该可以轻松绑定到xaml。

相关问题