简体   繁体   English

如何在C#/ Linq中获取定列名称的值?

[英]how to get value of a definite Column name in c# / Linq?

I want to know if it possible to get value of a definite columns name ? 我想知道是否可以获取确定的列名称的值? For exemple SELECT NAME FROM PERSON; 例如, SELECT NAME FROM PERSON;人中SELECT NAME FROM PERSON;

string NAME; <--- Column name
string fundPerson;
fundPerson = context.PERSON.Where(a => a... == NAME);

The problem is that the column name can change, it is not always the "NAME" column. 问题在于列名可以更改,它并不总是“ NAME”列。 Hence I need a solution where I can dynamically pass a column name to the query. 因此,我需要一个可以动态将列名传递给查询的解决方案。

You want to the source code in C# to create a linq query that compiles to SELECT NAME FROM PERSON under Linq to SQL or Linq to Entity Framework? 您想在C#中的源代码中创建一个linq查询,该查询可以在Linq to SQL或Linq to Entity Framework下编译为SELECT NAME FROM PERSON吗?

IEnumerable<string> names = from x in context.PERSONS
                            select x.Name;

OR 要么

IEnumerable<string> names = context.PERSONS.Select(x => x.Name);

In Monad parlance you want a projection onto the Name property. 用Monad的话来说,您希望投影到Name属性上。

EDIT : You want to dynamically state which column? 编辑:您想动态声明哪个列?

string columnName = "Name";
ParameterExpression personExpression = Expression.Parameter(typeof(Person), "p");
Expression<Func<Person, string>> column = Expression.Lambda<Func<Person, string>>(Expression.PropertyOrField(personExpression, columnName), personExpression);

IEnumerable<string> things = context.PERSONS.Select(column);

尝试这个

fundPerson = context.PERSON.Where(a=>a... == NAME).Select(a=>a.NAME).SingleOrDefault();

Your question is a bit misleading.. Are you after a collection of names, like what you would get from running the SQL "SELECT Name FROM Person"? 您的问题有点令人误解。您是否在收集了一系列名称,例如通过运行SQL“ SELECT Person FROM Person”会得到什么?

If so, using Linq-to-sql syntax: 如果是这样,请使用Linq-to-sql语法:

var people = from p in context.PERSON select a.NAME;

If you're trying to find a specific person, based on the NAME string? 如果您要根据NAME字符串查找特定的人?

string name = "barry";
var person = from p in context.PERSON select a where a.NAME.Contains(name);

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

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