LINQ集团结束了

时间:2012-01-30 14:07:35

标签: c# linq

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

无论如何,这是我有点人为的例子,我希望它可以解决我的问题:

假设我们有这些课程

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

正如您所看到的,WordExamples列表包含不完整的单词示例,因为它们没有实例化的WordsWithWord列表。

所以我需要的是一些整洁的Linq,它会设置它。即就像是: foreach wordExample获取包含该单词的句子的子集,并将其分配给sentencesWithWord。 (Withouth嵌套for循环)

修改 添加公共访问修饰符

4 个答案:

答案 0 :(得分:2)

你所追求的并不是很清楚,但我怀疑你想要

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

答案 1 :(得分:0)

由于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();
}

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

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