linq变量到c中的datagridview
我在Linq中有一个简单的查询,它按字长获取字符组,下面是代码linq变量到c中的datagridview,linq,c#-4.0,datagridview,Linq,C# 4.0,Datagridview,我在Linq中有一个简单的查询,它按字长获取字符组,下面是代码 string sentence = "This is sample linq query"; string[] words = sentence.Split(' '); var query = from word in words group word by word.Length into gr
string sentence = "This is sample linq query";
string[] words = sentence.Split(' ');
var query = from word in words
group word by word.Length into gr
orderby gr.Key ascending
select new { Length = gr.Key, Words = gr };
foreach (var obj in query)
{
Console.WriteLine("Word of Length: {0}", obj.Length);
foreach (string word in obj.Words)
{
Console.WriteLine("{0}", word);
}
Console.WriteLine();
}
它工作正常,现在我想通过将上述记录放入DataGridView,将其转换为windows窗体应用程序,因此我实现如下
string sentence = "This is sample linq query";
string[] words = sentence.Split(' ');
var query = from word in words
group word by word.Length into gr
orderby gr.Key ascending
select new { Length = gr.Key, Words = gr };
dataGridView1.DataSource = query.ToList();
但是在这里,我只得到DataGridView中的第一列长度,而不是Word列,我还需要做些什么才能得到这两列。在您的例子中,分组中的Word部分由一个IGrouping组成,它不能由datagrid显示。尝试按如下方式连接单词:
var query = from word in words
group word by word.Length into gr
orderby gr.Key ascending
select new { Length = gr.Key, Words = gr.Aggregate((left, right)=>string.Format("{0}, {1}", left, right)) };
然后您将在网格中看到两列,一列的长度为,另一列的长度为现在再次连接的相同长度的单词