Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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;

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. Hence I need a solution where I can dynamically pass a column name to the query.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...