根据长度对单词进行分组c#

时间:2012-07-07 17:32:19

标签: c# linq c#-4.0

是否可以根据长度将字符串分组到数组中?我正在尝试以下代码,但它不起作用。谢谢。

string [] groups =
      from word in words.split(' ')
      orderby word ascending
      group word by word.Length into lengthGroups
      orderby lengthGroups.Key descending
      select new { Length = lengthGroups.Key, Words = lengthGroups };

2 个答案:

答案 0 :(得分:3)

由于查询返回匿名类型的列表,您应该使用var关键字:

var sentence = "Here are a few words in a sentence";
var words = sentence.Split(' ');

var groups =
  from word in words
  orderby word ascending
  group word by word.Length into lengthGroups
  orderby lengthGroups.Key descending
  select new { Length = lengthGroups.Key, Words = lengthGroups };

// Test the results
foreach (var lengthGroup in groups)
{
    Console.WriteLine(lengthGroup.Length);

    foreach(var word in lengthGroup.Words)
    {
        Console.WriteLine(word);
    }
}

您还可以使用动态IEnumerable

IEnumerable<dynamic> groups =
  from word in words
  orderby word ascending
  group word by word.Length into lengthGroups
  orderby lengthGroups.Key descending
  select new { Length = lengthGroups.Key, Words = lengthGroups };

由于您的结果不是字符串列表,因此它是匿名类型的列表,您无法将其强制转换为字符串数组。如果您想:

,可以将其强制转换为动态类型数组
dynamic[] myArray = groups.ToArray();

答案 1 :(得分:1)

//string[] words = new string[] { "as", "asdf", "asdf", "asdfsafasd" };
//string[] words = "as asdf asdf asdfsafasd".Split(' ');

var groups = "as asdf asdf asdfsafasd".Split(' ').GroupBy(x => x.Length);

foreach (var lengthgroup in groups)
{
    foreach (var word in lengthgroup)
    {
        Console.WriteLine(word.Length + " : " + word);
    }
}