1

我在 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 而不是 Words 列中获得第一列(长度),我还需要做些什么来获得这两列。

4

1 回答 1

0

在您的情况下,分组的单词部分由 IGrouping 组成 - 数据网格无法显示。尝试按如下方式连接单词:

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)) };

然后你会在网格中看到两列,一列是长度,另一列是现在再次连接的那个长度的单词。

于 2012-09-18T20:38:32.130 回答