首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >LINQ GroupBy over

LINQ GroupBy over
EN

Stack Overflow用户
提问于 2012-01-30 14:07:35
回答 4查看 124关注 0票数 1

这件事可能已经处理好了,所以我提前向你道歉。

总之,这是我的一些人为的例子,我希望它能让我明白我的问题:

假设我们有这些课

代码语言:javascript
复制
class WordExamples 
{
   public string word;
   public List<Sentence> sentencesWithWord;
   //constructor
   public WordExamples(string word) {
      this.word = word;
   }
}

class Sentence 
{
   public List<string> words;
}

然后我们建立了两个列表:

代码语言:javascript
复制
List<Sentence> sentences = GetSomeSentences();
List<WordExamples> wordExamples = 
    GetSomeWords().Select(w=>new WordExamples(w));

如您所见,WordExamples列表包含不完整的word示例,因为它们没有实例化sentencesWithWord列表。

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

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-01-30 14:15:26

由于LINQ是一种查询语言,而不是赋值语言,所以应该使用循环:

代码语言:javascript
复制
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();
}
票数 0
EN

Stack Overflow用户

发布于 2012-01-30 14:14:35

不太清楚你想要什么,但我怀疑你想要:

代码语言:javascript
复制
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类,您可以拥有:

代码语言:javascript
复制
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的一个元素,请注意.

不管怎么说,有了这些,你可以用:

代码语言:javascript
复制
var wordExamples = from sentence in sentences
                   from word in sentence.Words
                   group sentence by word into g
                   select new WordExample(g.Key, g.ToList());
票数 2
EN

Stack Overflow用户

发布于 2012-01-30 14:51:36

代码语言:javascript
复制
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;
}
);

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9065092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档