DataGridView AddRange, Cast IEnumerable <object []> in DataGridViewRow [] (if possible, using LINQ)

If we want to add a string to DataGridView, in addition to adding an object DataGridViewRow, we could do this by passing an array of the object ( object[])

dgv.Rows.Add(objArray); //objArray is of type object[]

However, if we want to add a series of lines to DataGridView, we cannot pass IEnumerable<object[]>, but we can only transmitDataGridViewRow[]

dgv.Rows.AddRange(ienumObjArray); //not allowed, ienumObjArray is of type IEnumerable<object[]>
dgv.Rows.AddRange(dgvRows); //allowed, dgvRows is DataGridViewRow[]

My question is: is there a way to drop IEnumerable<object[]>in DataGridViewRow[](if possible with LINQ) so that we can do something like this

dgv.Rows.AddRange(ienumObjArray.DoSomethingWithLinq(x => doSomething)); 

and no need to add object[]one by one?

foreach(object[] objArray in ienumObjArray)
    dgv.Rows.Add(objArray); //adding one by one, is it possible to get rid this of?

Edit:

It is done on WinForms

Edit 2:

applying @abatishchev's suggestion (without AddRange), I came across a strange result. If I put:

ienumObjArray.Select(objArr => dgv.Rows.Add(objArr)); 

or

var result = ienumObjArray.Select(objArr => dgv.Rows.Add(objArr)); 

dgv .

,

ienumObjArray.Select(objArr => dgv.Rows.Add(objArr)).ToArray();
ienumObjArray.Select(objArr => dgv.Rows.Add(objArr)).ToList();
ienumObjArray.Select(objArr => dgv.Rows.Add(objArr)).Count();

or 

var result = ienumObjArray.Select(objArr => dgv.Rows.Add(objArr))
foreach(int i in result){
    //do something
}

! ?

+4
2

AddRange DataGridViewRowCollection, IEnumerable<object[]> :

public static class DataGridViewExtensions
{
    public static void AddRange(this DataGridViewRowCollection collection, IEnumerable<object[]> rows)
    {
        foreach (object[] item in rows)
        {
            collection.Add(item);
        }
    }
}

:

+3

DataGridViewRow, linq IEnumerable<object[]>, AddRange of DataGridViewRowCollection, . DataGridViewRow, :

dgv.Rows.AddRange(ienumObjArray.Select(cols => PrepareDataGridViewRow(dgv,cols)).ToArray());

.

private static DataGridViewRow PrepareDataGridViewRow(DataGridView dgv, object[] cols)
{
    var result = new DataGridViewRow();
    result.CreateCells(dgv,cols);
    return result;
};
+1

Source: https://habr.com/ru/post/1623858/


All Articles