C# 如何使用Linq从DataGridView检索非null或空白字符串列表

C# 如何使用Linq从DataGridView检索非null或空白字符串列表,c#,linq,datagridview,C#,Linq,Datagridview,当然,我的问题正是我的标题所说的。我对林克还是很陌生。但它的用处使我必须学习它 我有一个正在进行的查询。我觉得我就快到了,但是我得到了空列表,尽管DataGridView中有很多名为DataView的东西 这是我目前的疑问 List<List<string>> newData = new List<List<string>>(); newData = DataView.Rows.OfType<DataGridViewRo

当然,我的问题正是我的标题所说的。我对林克还是很陌生。但它的用处使我必须学习它

我有一个正在进行的查询。我觉得我就快到了,但是我得到了空列表,尽管DataGridView中有很多名为DataView的东西

这是我目前的疑问

     List<List<string>> newData = new List<List<string>>();
     newData =  DataView.Rows.OfType<DataGridViewRow>()
          .Select(row => row.Cells.OfType<DataGridViewCell>()
            .Select(cell => cell.Value.ToString())
            .Where(s => !string.IsNullOrWhiteSpace(s))
            .ToList()
          .ToList()) as List<List<string>>;
List newData=newlist();
newData=DataView.Rows.OfType()
.Select(row=>row.Cells.OfType())
.Select(cell=>cell.Value.ToString())
.Where(s=>!string.IsNullOrWhiteSpace)
托利斯先生()
.ToList())作为列表;

我的查询大致基于我看到的

LINQ语句返回的实际上是一个
IEnumerable

当您使用
as List
强制转换结果时,您将得到
null
。。。因为结果实际上不是那种类型

目前,您有这个,这是多余的:

.ToList().ToList()
相应地修改LINQ语句:

List<List<string>> newData =
    dataGridView1.Rows.OfType<DataGridViewRow>()
                 .Select(row => row.Cells.OfType<DataGridViewCell>()
                                   .Select(cell => cell.Value.ToString())
                                   .Where(s => !string.IsNullOrWhiteSpace(s))
                                   .ToList())
                 .ToList();
列出新数据=
dataGridView1.Rows.OfType()类型
.Select(row=>row.Cells.OfType())
.Select(cell=>cell.Value.ToString())
.Where(s=>!string.IsNullOrWhiteSpace)
.ToList())
.ToList();

首先,删除
as List
,然后将
newData=…
替换为
var something=…
,以查看表达式返回的内容。因此,当我这样做时,我会看到var中包含正确的内容。但是如果我尝试将var转换为一个列表,谢谢,这是可行的。我的括号好像放错地方了。