2

我将 linq 结果数据绑定到数据网格,但没有任何结果。这是我的代码

        List<SearchResult> list = new List<SearchResult>() {
        new SearchResult(){ID=1,Title="Geo Prism 1995 GEO* - ABS #16213899"},
        new SearchResult(){ID=2,Title="Excavator JCB - ECU P/N: 728/35700"},
        new SearchResult(){ID=3,Title="Geo Prism GEO 1995 - ABS #16213899"},
        new SearchResult(){ID=4,Title="JCB Excavator JCB- ECU P/N: 728/35700"},
        new SearchResult(){ID=5,Title="Geo Prism GEO,GEO 1995 - ABS #16213899 GEO"},
        new SearchResult(){ID=6,Title="dog"},
        };

        var to_search = new[] { "Geo", "JCB" }.Select(x => x.ToLower()).ToArray();
        var result = from searchResult in list
                     let title = searchResult.Title.ToLower()
                     let key_string = to_search.FirstOrDefault(ts => title.Contains(ts))
                     orderby key_string == null ? -1 : title.Split(new[] { key_string }, StringSplitOptions.None).Length descending
                     group searchResult by key_string into Group
                     orderby Group.Count() descending
                     select Group;

        dataGridView2.DataSource = result;

当我运行上面的代码 datagrid 什么都没有显示,但我期望 datagrid 应该显示ID 和 Title

然后我添加了更多的行

List<SearchResult> listFinal = new List<SearchResult>();
foreach (var group in result)
{
     foreach (var item in group)
     {
        listFinal.Add(new SearchResult() { ID = item.ID, Title = item.Title });
     }
 }
 dataGridView2.DataSource = listFinal;

现在 datagrid 正在显示数据。所以我的问题是......是否有任何捷径可以将结果转换为列表,因此我可以通过循环迭代将列表直接绑定到数据网格并创建一个新列表并在绑定之前将其填充。寻求指导。谢谢

4

2 回答 2

3

是的,只需在您的 LINQ 查询上调用.SelectMany().ToList() 即可。

dataGridView2.DataSource = result.SelectMany(e => e).ToList();

或使用适当的构造函数创建您的列表:

dataGridView2.DataSource = new List(result.SelectMany(e => e));
于 2012-07-10T12:53:12.073 回答
1

这应该这样做

   var result = (from searchResult in list
                         let title = searchResult.Title.ToLower()
                         let key_string = to_search.FirstOrDefault(ts => title.Contains(ts))
                         orderby key_string == null ? -1 : title.Split(new[] { key_string }, StringSplitOptions.None).Length descending
                         group searchResult by key_string into Group
                         orderby Group.Count() descending
                         select Group).ToList();
于 2012-07-10T12:52:54.497 回答