Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
linq变量到c中的datagridview_Linq_C# 4.0_Datagridview - Fatal编程技术网

linq变量到c中的datagridview

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

我在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
                        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)) };
然后您将在网格中看到两列,一列的长度为,另一列的长度为现在再次连接的相同长度的单词