简体   繁体   English

使用 Linq 进行多列选择

[英]Multiple column selection using Linq

I have the below SQL query.我有以下 SQL 查询。 Not sure how to convert this to Linq.不确定如何将其转换为 Linq。

select u.userid, u.firstname, u.lastname,companyname,city,state 
from user u 
order by  u.lastname, u.firstname

I've tried this:我试过这个:

public ActionResult Users() {
  dbEntities entities1 = new dbEntities();
  return View(from users in entities1.u_user select userid,firstname,lastname,companyname,city,state);
} 

The exact translation is :准确的翻译是:

Db.User.Select(p=> new {
    userid = p.userId,
    firstName = p.firstName,
    lastName = p.lastName,
    companyName p = p.companyName,
    city = p.City,
    state = p.State }).OrderBy(p=>p.lastName).ThenBy(p=>p.firstName)

Where you create a dynamic object containing only some fields you want.您可以在其中创建仅包含您想要的某些字段的动态object

If you want all properties of your entity, you can use simply :如果您想要实体的所有属性,您可以简单地使用:

Db.User.OrderBy(p=>p.lastName).ThenBy(p=>p.firstName)

In general, assuming C#, convert SQL to LINQ by converting phrases in LINQ comprehension syntax order, and if SQL has table aliases, use them in LINQ as range variables.一般来说,假设C#,通过将短语按LINQ理解语法顺序转换来将SQL转换为LINQ,如果SQL有表别名,则在LINQ中将它们用作范围变量。 Convert non-range functions like TOP or DISTINCT as function calls outside the rest of the expression.TOPDISTINCT等非范围函数转换为表达式其余部分之外的函数调用。

var ans = from u in user
          orderby u.lastname, u.firstname
          select new { u.userid, u.firstname, u.lastname, u.companyname, u.city, u.state };

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

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