[英]Convert contents of DataGridView to List in C#
获取 DataGridView 的内容并将这些值放入 C# 中的列表的最佳方法是什么?
List<MyItem> items = new List<MyItem>();
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
MyItem item = new MyItem();
foreach (DataGridViewCell dc in dr.Cells)
{
...build out MyItem....based on DataGridViewCell.OwningColumn and DataGridViewCell.Value
}
items.Add(item);
}
如果使用DataSource绑定列表,则可以使用以下命令转换回:
List<Class> myClass = DataGridView.DataSource as List<Class>;
Or a linq way 或者是一种linq方式
var list = (from row in dataGridView1.Rows.Cast<DataGridViewRow>()
from cell in row.Cells.Cast<DataGridViewCell>()
select new
{
//project into your new class from the row and cell vars.
}).ToList();
var Result = dataGridView1.Rows.OfType<DataGridViewRow>().Select(
r => r.Cells.OfType<DataGridViewCell>().Select(c => c.Value).ToArray()).ToList();
or to get a string dictionary of the values 或者获取值的字符串字典
var Result = dataGridView1.Rows.OfType<DataGridViewRow>().Select(
r => r.Cells.OfType<DataGridViewCell>().ToDictionary(c => dataGridView1.Columns[c.OwningColumn].HeaderText, c => (c.Value ?? "").ToString()
).ToList();
IEnumerable.OfType<TResult>
extension method can be your best friend here. IEnumerable.OfType<TResult>
扩展方法可以成为你最好的朋友。 Here is how I would have done it through a LINQ query: 这是我如何通过LINQ查询完成它:
List<MyItem> items = new List<MyItem>();
dataGridView1.Rows.OfType<DataGridViewRow>().ToList<DataGridViewRow>().ForEach(
row =>
{
foreach (DataGridViewCell cell in row.Cells)
{
//I've assumed imaginary properties ColName and ColValue in MyItem class
items.Add(new MyItem { ColName = cell.OwningColumn.Name, ColValue = cell.Value });
}
});
VB: VB:
Dim lst As List(Of DataGridViewRow) = Me.MasterDataGridView.Rows.Cast(Of DataGridViewRow).AsEnumerable.ToList
C#: C#:
List<DataGridViewRow> lst = this.MasterDataGridView.Rows.Cast<DataGridViewRow>.AsEnumerable.ToList;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.