C# lambda与此Linq表达式的等效值是什么?

C# lambda与此Linq表达式的等效值是什么?,c#,linq,lambda,C#,Linq,Lambda,lambda与此Linq表达式的等效值是什么 var authorList = new List<Author>(); var postList = new List<Post>(); var e = (from p in postList from a in authorList where p.AuthorId == a.Id select new { p, a }); var authorList=new Li

lambda与此Linq表达式的等效值是什么

var authorList = new List<Author>();
var postList = new List<Post>();
var e = (from p in postList
         from a in authorList
         where p.AuthorId == a.Id
         select new { p, a });
var authorList=new List();
var postList=新列表();
var e=(来自postList中的p
来自作者列表中的
其中p.AuthorId==a.Id
选择新的{p,a});

我相信与此等效的直接方法语法是

postList.SelectMany(p => autorList.Where(a => a.Id == p.AutorId).Select(a => new {p, a}));

这将产生一个扁平的列表,每个帖子和作者的帖子,如果该帖子有一个作者。

< P>一个选择要考虑的是使用--因为你正在有效地做一个内部连接:

var results = authorList.Join(postList, z => z.Id, y => y.AuthorId,
    (a, p) => new { p, a });
用于比较两者的示例程序将生成相同的结果:

using System;
using System.Collections.Generic;
using System.Linq;

namespace TestProgram
{
    class Program
    {
        public static void Main()
        {
            var authorList = new List<Author>
            {
                new Author() {Id = 3},
                new Author() {Id = 4},
                new Author() {Id = 5}
            };

            var postList = new List<Post>
            {
                new Post() {AuthorId = 1},
                new Post() {AuthorId = 1},
                new Post() {AuthorId = 3},
                new Post() {AuthorId = 3},
                new Post() {AuthorId = 4},
                new Post() {AuthorId = 6}
            };

            var e = (from p in postList
                     from a in authorList
                     where p.AuthorId == a.Id
                     select new { p, a });

            var f = authorList.Join(postList, z => z.Id, y => y.AuthorId, (a, p) => new { p, a });

            Console.WriteLine(e.SequenceEqual(f));
            Console.ReadLine();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
名称空间测试程序
{
班级计划
{
公共静态void Main()
{
var authorList=新列表
{
新作者(){Id=3},
新作者(){Id=4},
新作者(){Id=5}
};
var postList=新列表
{
new Post(){AuthorId=1},
new Post(){AuthorId=1},
new Post(){AuthorId=3},
new Post(){AuthorId=3},
new Post(){AuthorId=4},
新建Post(){AuthorId=6}
};
var e=(来自postList中的p
来自作者列表中的
其中p.AuthorId==a.Id
选择新的{p,a});
var f=authorList.Join(postList,z=>z.Id,y=>y.AuthorId,(a,p)=>new{p,a});
控制台写入线(e.SequenceEqual(f));
Console.ReadLine();
}
}
}

可能与where子句重复,其功能类似于内部联接。e、 g.对于反对者,我想了解更多关于如何改进答案的信息。请随意留言。