如何计算datagridview中的重复项

时间:2012-03-07 10:56:31

标签: c# winforms datagridview

我有datagridview1列填充了数据:Room1,Room2,Room3,Room1,Room3,还有一些数据在行中,所以它是这样的:

Name, Time, Room
name1, 10,  Room1
name2, 44,  Room2
name3, 1,   Room3
name4, 12,  Room1
.................

我想要的是计算数字或重复次数 - 2x Room1,1x Room2,2x Room3并添加累积时间值。

所以看起来应该是这样的:

Room    |  Cumulative_Time
-------------------------
Room1   |  22 
Room2   |  44

并将其添加到另一个datagridview .. 任何想法怎么做?

3 个答案:

答案 0 :(得分:1)

您可以使用lambda和linq风格:

public List<Room> GetRooms()
{
    return new List<Room>(){new Room(){Name = "Room1", Time= 10},
                            new Room(){Name = "Room1", Time= 20},
                            new Room(){Name = "Room2", Time= 10},
                            new Room(){Name = "Room2", Time= 30},
                            new Room(){Name = "Room2", Time= 50},
                            new Room(){Name = "Room4", Time= 25},
                            new Room(){Name = "Room3", Time= 50},
                            new Room(){Name = "Room3", Time= 15},
                            new Room(){Name = "Room3", Time= 30},
                            new Room(){Name = "Room3", Time= 40}};
}

[TestMethod]
public void CheckSumsLambda()
{
    var rooms = GetRooms();
    var results = rooms.GroupBy(x => x.Name).Select(x => new { RoomName = x.Key, Occurences = x.Count(), Cumulativetime = x.Sum(y => y.Time) });

    Console.WriteLine("Lambda flavour");
    foreach (var result in results)
    {                 
        Console.WriteLine("{0}x {1}  | {2}", result.Occurences, result.RoomName, result.Cumulativetime);               
    }

}

[TestMethod]
public void CheckSumsLinq()
{
    var rooms = GetRooms();
    var results = from r in rooms
                    group r by r.Name
                        into g
                        select new { RoomName = g.Key, Occurences = g.Count(), Cumulativetime = g.Sum(y => y.Time) };

    Console.WriteLine("Linq flavour");
    foreach (var result in results)
    {
        Console.WriteLine("{0}x {1}  | {2}", result.Occurences, result.RoomName, result.Cumulativetime);
    }

}

输出:

lambda version

linq version

答案 1 :(得分:0)

如果您的数据来自查询,您可以使用在时间上使用求和函数的查询填充第二个网格,按房间字段分组

SELECT Room, Sum(Time) from data_table group by Room

如果您不想/不能使用SQL查询,可以使用Linq来完成,但我无法帮助您解决语法...

答案 2 :(得分:0)

假设您使用POCO作为您的数据源,这应该可以解决您的问题。

// Get data from DataGridView
var dts = DataGridView.DataSource;

// Get list of rooms
var rooms = dts.Select(d=>d.Room).Distinct();

// Populate new DataGrid
NewDataGridView.DataSource = rooms
.Select(r => new {Room = r, 
Cumulative_Time = dts.Where(d => d.room == r).Select(d => d.time).Sum()});