C#加入/使用LINQ和Lambda在哪里 [英] C# Joins/Where with Linq and Lambda
本文介绍了C#加入/使用LINQ和Lambda在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有写在LINQ和LAMBDA查询的麻烦。到目前为止,我得到了很多错误,这是我的code:
I'm having trouble with a query written in Linq and Lambda. So far, I'm getting a lot of errors here's my code:
int id = 1;
var query = database.Posts.Join(database.Post_Metas,
post => database.Posts.Where(x => x.ID == id),
meta => database.Post_Metas.Where(x => x.Post_ID == id),
(post, meta) => new { Post = post, Meta = meta });
我是新来使用LINQ,所以我不知道该查询是正确的。
I'm new to using Linq, so I'm not sure if this query is correct.
推荐答案
我觉得,如果你熟悉SQL语法,使用LINQ查询语法更清晰,更自然,更容易发现错误:
I find that if you're familiar with SQL syntax, using the LINQ query syntax is much clearer, more natural, and makes it easier to spot errors:
var id = 1;
var query =
from post in database.Posts
join meta in database.Post_Metas on post.ID equals meta.Post_ID
where post.ID == id
select new { Post = post, Meta = meta };
如果你真的坚持使用lambda表达式,虽然是,你的语法是相当多了。下面是相同的查询,使用LINQ扩展方法:
If you're really stuck on using lambdas though, your syntax is quite a bit off. Here's the same query, using the LINQ extension methods:
var id = 1;
var query = database.Posts // your starting point - table in the "from" statement
.Join(database.Post_Metas, // the source table of the inner join
post => post.ID, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
meta => meta.Post_ID, // Select the foreign key (the second part of the "on" clause)
(post, meta) => new { Post = post, Meta = meta }) // selection
.Where(postAndMeta => postAndMeta.Post.ID == id); // where statement
这篇关于C#加入/使用LINQ和Lambda在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文