如何在Linq中过滤子集合

MAC*_*MAC 3 linq lambda filtering inner-join

我需要使用单个linq查询过滤linq中实体的子元素.这可能吗?

假设我有两个相关的表.诗歌和诗歌翻译.LINQ to SQL创建的实体是这样的,我有一个Verse对象,它包含一个子对象,它是VerseTranslation的集合.

现在,如果我有以下linq查询

var res = from v in dc.Verses
                  where v.id = 1
                  select v;
Run Code Online (Sandbox Code Playgroud)

我得到一个诗歌集合,其id为1,每个诗歌对象包含VerseTranslations中的所有子对象.

我还想做的是过滤Verse Translations的子列表.

到目前为止,我能够想出的唯一方法是使用新的匿名类型或其他方式.如下

var res= from v in dc.Verses
                   select new myType
                   {
                       VerseId = v.VerseId,
                       VText = v.Text,
                       VerseTranslations = (from trans in v.VerseTranslations
                                               where languageId==trans.LanguageId
                                               select trans
                   };
Run Code Online (Sandbox Code Playgroud)

上面的代码有效,但我必须为它声明一个新类.有没有办法以这样的方式执行它,以便子表上的过滤可以合并到第一个linq查询中,以便不必声明新的类.

此致,MAC

MAC*_*MAC 8

所以我终于得到了工作,感谢Shiraz提供的指针.

        DataLoadOptions options = new DataLoadOptions();
        options.AssociateWith<Verse>(item => item.VerseTranslation.Where(t => languageId.Contains(t.LanguageId)));

        dc.LoadOptions = options;

        var res = from s in dc.Verse
                   select s;
Run Code Online (Sandbox Code Playgroud)

这不需要投影或使用新的扩展类.

感谢所有输入的人.