C# 使用 linq 从 var 中提取一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10600690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:26:37  来源:igfitidea点击:

extract one column from a var using linq

c#linq-to-entities

提问by Piyush Sardana

i have something like this

我有这样的东西

var emp = db.Employees.toList();

in my employees table i have emp name, emp id and salary, using linq with lambda expressions, how do i access emp id in some another variable. I have tried looking up for it, couldn't find a solution which does it using linq with lambda expressions

在我的员工表中,我有 emp 名称、emp id 和工资,使用 linq 和 lambda 表达式,我如何在另一个变量中访问 emp id。我尝试查找它,但找不到使用 linq 和 lambda 表达式的解决方案

var employeeLeaves = db.Leaves
     .Include("Employee")
     .Include("Employee.Manager")
     .Where(l => l.Status.Id == 1)
     .GroupBy(l => l.Employee.Manager.Id)
     .Select(l => l.GroupBy(k=>k.Employee.Id).Select(j=>j.GroupBy(??p=>p.GroupId)))
     .ToList(); 

this is the actual query i have,dont ask me how i wrote it..:P now i want to get id column from employeeLeaves and store it in some another variable

这是我的实际查询,不要问我是怎么写的..:P 现在我想从employeeLeaves 获取id 列并将其存储在另一个变量中

采纳答案by Jon Skeet

It's not entirely clear what you're trying to do, which is why you've got so many answers with different approaches. If you're trying to turn the "collection of employees" into a "collection of IDs" then you want something like this:

并不完全清楚你想要做什么,这就是为什么你有这么多不同方法的答案。如果您想将“员工集合”变成“ID 集合”,那么您需要这样的东西:

var ids = emp.Select(x => x.Id);

Or more directly:

或者更直接:

var ids = db.Employees.Select(x => x.Id);

(Optionally with ToListat the end of each of these.)

(可选地ToList在每个末尾。)

I would strongly advise you to learn LINQ (and the somewhat-related languages features such as var) thoroughly, from scratch, with the help of a good book or tutorial. Learning bits piecemeal by just finding samples which do something a bit like what you want is not a good approach, IMO.

我强烈建议您在var一本好书或教程的帮助下,从头开始彻底学习 LINQ(以及有些相关的语言功能,例如)。IMO,仅通过查找做一些类似于您想要的事情的样本来零碎地学习并不是一个好方法。

回答by Ravi Gadag

Try this syntax:

试试这个语法:

var empIds = db.Employees.Select(e=>e.EmpID)

回答by Arion

You can use the select. Maybe something like this:

您可以使用select. 也许是这样的:

var result=db.Employees
              .Select(s=>s.emp_id);

回答by archil

var empId = db.Employees.Single(x => x.id == 5).Id;

回答by Mohwaili

Database.Tablename.Single(x => x.id == anyId)

This should select single row

这应该选择单行