如何将LINQ结果绑定到datagrid

时间:2012-07-10 12:51:52

标签: c# linq

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

        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和标题

然后我添加一些像

这样的行
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正在显示数据。所以我的问题是....是否有任何捷径方式将结果转换为列表,因此我可以使用循环迭代将列表直接绑定到datagrid并创建新列表并在绑定之前填充它。寻求指导。感谢

2 个答案:

答案 0 :(得分:3)

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

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

或使用appropriate constructor创建您的列表:

dataGridView2.DataSource = new List(result.SelectMany(e => e));

答案 1 :(得分: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();