什么是lambda等同于这个Linq表达式?

时间:2018-05-16 22:49:15

标签: c# linq lambda

与此Linq表达式相当的lambda是什么?

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

2 个答案:

答案 0 :(得分:2)

我相信直接方法语法相当于

$1

如果该帖子有作者,那将会产生每个帖子的平面列表和所述帖子的作者。

答案 1 :(得分:0)

要考虑的一个选择是使用Join - 因为您实际上在进行内部联接:

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