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.
Use as
var data = ctx.tblTable
.Where(e => e.Id == Id && e.Name == name)
.SingleOrDefault().ColumnName;
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);
}
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));
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.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.