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

c# dynamic-linq linq

Question

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.

1
1
4/7/2014 8:55:27 AM

Accepted Answer

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);
2
4/7/2014 8:40:01 AM

Popular Answer

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"?

If so, using Linq-to-sql syntax:

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

If you're trying to find a specific person, based on the NAME string?

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


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow