Reputation: 34188
i bind linq result data to datagrid but nothing comes. here is my code
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;
when i run the above code datagrid showing nothing but i was expecting datagrid should show ID and Title
then i add some more line like
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;
now datagrid is showing data. so my question is that....is there any short cut way to convert result to list as a result i can bind list directly to datagrid with iterate in loop and create a new list and fill it up before binding. looking for guidance. thanks
Upvotes: 2
Views: 5569
Reputation: 101032
Yes, just call .SelectMany() and .ToList() on your LINQ query.
dataGridView2.DataSource = result.SelectMany(e => e).ToList();
or create your List with the appropriate constructor:
dataGridView2.DataSource = new List(result.SelectMany(e => e));
Upvotes: 3
Reputation: 4327
This should do it
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();
Upvotes: 1