Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...