LINQ GroupBy over

本文关键字:over GroupBy LINQ | 更新日期: 2023-09-27 18:21:48

这可能已经处理好了,所以我提前为此道歉。

无论如何,这是我有点做作的例子,我希望它能让我的问题明白:

假设我们有这些类

class WordExamples 
{
   public string word;
   public List<Sentence> sentencesWithWord;
   //constructor
   public WordExamples(string word) {
      this.word = word;
   }
}
class Sentence 
{
   public List<string> words;
}

然后我们设置了两个列表:

List<Sentence> sentences = GetSomeSentences();
List<WordExamples> wordExamples = 
    GetSomeWords().Select(w=>new WordExamples(w));

正如你所看到的,单词示例列表中包含的单词示例是不完整的,因为它们没有实例化单词列表中的句子。

所以我需要的是一些整洁的林克来设置这个。例如:foreach wordExample获取包含单词的句子子集,并将其分配给句子WithWord。(没有嵌套的循环)

编辑:添加公共访问修饰符

LINQ GroupBy over

目前还不清楚你想要什么,但我怀疑你想要:

foreach (var example in wordExamples)
{
    Console.WriteLine("Word {0}", example.Key);
    foreach (var sentence in example)
    {
        // I assume you've really got the full sentence here...
        Console.WriteLine("  {0}", string.Join(" ", sentence.Words));
    }
}

编辑:如果真的需要WordExamples类,可以使用:

public class WordExamples 
{
   public string Word { get; private set; }
   public List<Sentence> SentencesWithWord { get; private set; }
   public WordExamples(string word, List<Sentences> sentences) {
      Word = word;
      // TODO: Consider cloning instead
      SentencesWithWord = sentences;
   }
}

这基本上就像Lookup的一个元素,请注意。。。

不管怎样,有了它,你可以使用:

var wordExamples = from sentence in sentences
                   from word in sentence.Words
                   group sentence by word into g
                   select new WordExample(g.Key, g.ToList());

由于LINQ是查询语言,而不是赋值语言,因此应该使用循环:

List<WordExamples> wordExamples = GetSomeWords().Select(w=>new WordExamples(w))
                                                .ToList();

foreach(var wordExample in wordExamples)
{
    wordExample.sentencesWithWord
        = sentences.Where(x => x.words.Contains(wordExample.word)).ToList();
}
IEnumerable<WordExamples> wordExamples = GetSomeWords().Select(w=>
{
   var examples = new WordExamples(w);
   examples.sentencesWithWord = sentences.Where(s => s.words.Any(sw => sw == w)).ToList();
   return examples;
}
);

不要忘记设置正确的访问修饰符。

看起来你正在重新发明一个ILookup。

ILookup<string, Sentence> examples = GetSentences()
  .SelectMany(sentence => sentence.words, (sentence, word) => new {sentence, word} )
  .ToLookup(x => x.word, x => x.sentence);