使用Linq从DataGridViewCellCollection中选择值

时间:2018-10-19 12:06:20

标签: c# linq

我有一个DataGridViewCellCollection,想从单元格中读取值。稍后,我想创建一个新对象,将这些值作为构造函数参数传递并将它们添加到列表中。

        List<Connection> connections = new List<Connection>();

        for (int i = 0; i < dataGridView.Rows.Count; i++)
        {
            DataGridViewCellCollection cells = dataGridView.Rows[i].Cells; // current cellrow
            int firstValue = (int)cells[1].Tag; // convert to int
            int? secondValue = (int?)cells[0].Value; // convert to nullable int
            connections.Add(new Connection(firstValue, secondValue));
        }

        return connections;

Connection本身代表此struct

internal struct Connection
{
    public Connection(int firstID, int? secondID)
    {
        FirstID = firstID;
        SecondID = secondID;
    }

    public int FirstID { get; private set; }
    public int? SecondID { get; private set; }
}

我想用Linq重写此代码,但是如何选择特定的多个值并将结果转换为对象?

4 个答案:

答案 0 :(得分:4)

List<Connection> connections = dataGridView.Rows.OfType<DataGridViewRow>()
             .Select(x => new Connection((int)x.Cells[1].Tag, (int?)x.Cells[0].Value)
             .ToList();

return connections;

如@Mark Schultheiss所建议,使用.Cast<DataGridViewRow>可以更快,如下所示。

List<Connection> connections = dataGridView.Rows.Cast<DataGridViewRow>()
             .Select(x => new Connection((int)x.Cells[1].Tag, (int?)x.Cells[0].Value)
             .ToList();

return connections;

答案 1 :(得分:2)

from row in datagridView.Rows
let cells = row.Cells
let firstValue = (int)cells[1].Tag
let secondValue = (int?)cells[0].Value
select new Connection(firstValue, secondValue)

答案 2 :(得分:2)

var connections = dataGridView.Rows.OfType<DataGridViewRow>()
.Select(r => new Connection((int)r.Cells[1].Tag, (int?)r.Cells[0].Value))

答案 3 :(得分:1)

List<Connection> connections = dataGridView.Rows.OfType<DataGridViewRow>()
                                           .Select(CreateConnection)
                                           .ToList();

或者:

var connections = from row in dataGridView.Rows.OfType<DataGridViewRow>()
                  select CreateConnection(row);

方法CreateConnection:

private Connection CreateConnection(DataGridViewRow row)
{
    var firstValue = (int) row.Cells[1].Tag;
    var secondValue = (int?) row.Cells[0].Value;

    return new Connection(firstValue, secondValue);
}