4

In Table I have 5 columns :- name, age, dob, doj, entrydate.

string column = 'dob'; // This is dynamic

var data = ctx.tblTable
                    .Where(e => e.Id == Id && e.Name == name)
                    .Select(e => column).SingleOrDefault();

Unfortunately, this doesn't work. How to select a particular column in linq.

tereško
  • 56,151
  • 24
  • 92
  • 147
Anup
  • 8,072
  • 15
  • 62
  • 122
  • I don't know for sure, but I think you'll have to pull the full row down, then use reflection to grab the individual column. I like to think there's a better way, but that's the best one I know of. – Matthew Haugen Oct 06 '14 at 07:33
  • Perhaps this answer can help you too: http://stackoverflow.com/a/233505/858757 – Silvermind Oct 06 '14 at 08:17

5 Answers5

3

Use as

var data = ctx.tblTable
                .Where(e => e.Id == Id && e.Name == name)
                .SingleOrDefault().ColumnName;
Amit
  • 14,671
  • 8
  • 41
  • 63
3
string column = 'dob'; // This is dynamic

var data = ctx.tblTable
                    .Where(e => e.Id == Id && e.Name == name)
                    .ToList()
                    .Select(e => GetPropValue(e, column))
                    .FirstOrDefault();


public object GetPropValue(object obj, string propName)
{
     return obj.GetType().GetProperty(propName).GetValue(obj, null);
}
Arun Ghosh
  • 6,820
  • 1
  • 22
  • 37
  • I get this Error :- `{"LINQ to Entities does not recognize the method 'System.Object GetPropValue(System.Object, System.String)' method, and this method cannot be translated into a store expression."}` – Anup Oct 06 '14 at 08:28
  • This will pull the entire table in memory first – jeroenh Oct 06 '14 at 08:36
  • @jeroenh No. It will pull only the table entries matching query **Where(e => e.Id == Id && e.Name == name)** – Arun Ghosh Oct 06 '14 at 08:58
0

You can try

string column = 'dob';
var data = ctx.tblTable
                .Where(e => e.Id == Id && e.Name == name)
                .Select(e = > e.GetType().GetProperty(column).GetValue(e,null));
G J
  • 446
  • 8
  • 20
0

Use a SQL query instead? I assume that you are using Entity Framework. In that case use:

var columnValues = ctx.Database
         .SqlQuery<string>("SELECT " + column + " FROM tblTable WHERE Id = " + Id + " AND Name = '" + name + "'").ToList();

And make sure that column, Id and name do not allow SQL injection or unwanted values. You could do that with parametrized queries.

Manuel Schweigert
  • 4,406
  • 3
  • 17
  • 32
0
public class TestClass
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public DateTime Dob { get; set; }

        public void YourMethod()
        {
            List<TestClass> temp = new List<TestClass>();

            var x = from xyz in temp
                    where xyz.Name == "Name" && xyz.Id == new Guid()
                    select xyz.Dob;
        }
    }
Yeasin Abedin Siam
  • 1,459
  • 2
  • 17
  • 29