简体   繁体   English

与此Linq表达式等效的lambda是多少?

[英]What is the lambda equivalent to this Linq expression?

What is the lambda equivalent to this Linq expression? 与此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 });

I believe the direct method syntax equivalent of this would be 我相信等效的直接方法语法将是

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

Which will yield a flat list of each post and the author of said post, should that post have an author. 如果该帖子有一位作者,它将为每个帖子和该帖子的作者提供一个平面清单。

One option to consider would be the use of Join - since you are effectively doing an inner join: 要考虑的一种选择是使用Join因为您实际上是在进行内部Join

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

A sample program to compare the two are generating the same results: 比较这两个示例程序将产生相同的结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM