user9945420
user9945420

Reputation:

Select values from DataGridViewCellCollection using Linq

I have a DataGridViewCellCollection and want to read the values from the cells. Later I want to create a new object, pass in these values as constructor parameters and add them to a list.

        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 itself represents this 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; }
}

I would like to rewrite this code with Linq but how can I select specific multiple values and cast the result to an object?

Upvotes: 0

Views: 1251

Answers (4)

Karan
Karan

Reputation: 12629

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

return connections;

As suggested by @Mark Schultheiss, using .Cast<DataGridViewRow> can be faster as below.

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

return connections;

Upvotes: 3

Andy
Andy

Reputation: 79

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

Upvotes: 1

Rui Jarimba
Rui Jarimba

Reputation: 18024

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

Or:

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

Method 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);
}

Upvotes: 0

Jonas H&#248;gh
Jonas H&#248;gh

Reputation: 10874

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)

Upvotes: 1

Related Questions