这件事可能已经处理好了,所以我提前向你道歉。
总之,这是我的一些人为的例子,我希望它能让我明白我的问题:
假设我们有这些课
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列表包含不完整的word示例,因为它们没有实例化sentencesWithWord列表。
所以我需要的是一些整洁的Linq来设置这个。例如: foreach wordExample获取包含单词的句子子集,并将其分配给sentencesWithWord。(带有嵌套的循环,即)
编辑:添加公共访问修饰符的
发布于 2012-01-30 14:15:26
由于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();
}发布于 2012-01-30 14:14:35
不太清楚你想要什么,但我怀疑你想要:
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());发布于 2012-01-30 14:51:36
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;
}
);不要忘记设置正确的访问修饰符。
https://stackoverflow.com/questions/9065092
复制相似问题