简体   繁体   中英

LINQ Datagridview to comma delimited string

Hello is there a way to create a comma delimited string from an entire row from a datagridview.

Currently what I've been doing is something like so:

for(int y = 0; y < datagridview1.Rows.Count; y++)
{
    List<string> List = new List<string>();
    for(int x = 0; x < datagridview1.Columns.Count; x++)
    {
        List.Add(datagridview.Row[y].Cells[x].Value.ToString());
        //here i write it to a file doing something like string.Join(",",List)
    }
}

Is there a way to use LINQ or is there a way that I can condense this to a one liner?

You can use Enumerable.Range to emulate a for loop on integers:

var res = Enumerable.Range(0, datagridview1.Rows.Count)
    .Select(y => Enumerable.Range(0, datagridview1.Columns.Count)
        .Select(x => datagridview.Row[y].Cells[x].Value.ToString())
        .ToList()
    ).ToList();

The row and cell collections are all enumerable so you could make better use of LINQ here. You don't need to index the rows and columns, just enumerate over them.

var data =
    (from DataGridViewRow r in dataGridView.Rows
    select String.Join(",",
        from DataGridViewCell c in r.Cells
        select c.Value
    )).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM