You must Sign In to post a response.
  • Category: .NET

    How to get multiple column value in linq query


    I want to select multiple column in my query with where condition. The Additional column name is ProdName which i want to get the value and Where the "TotalUnits" = 0.

    IEnumerable<string> query = from rowValue in dt.AsEnumerable()
    select rowValue.Field<string>("TotalUnits");

    How can i do this. Above i can select single column only.
  • #769044

    We can get multiple columns values in the LINQ format in the following way.

    public NamePriceModel[] AllProducts()
    using (UserDataDataContext db = new UserDataDataContext())
    return db.mrobProducts.Where(x => x.Status == 1).Select(x => new NamePriceModel { Name = x.Name, Id = x.Id, Price = x.Price}).OrderBy(x => x.Id).ToArray();
    return null;

    The model is the important part in this implementation. So you should declare the model name with the parameters in the data logic layer.

    public class NamePriceModel
    public string Name {get; set;}
    public decimal? Price {get; set;}
    public int Id {get; set;}


  • #769052
    As the other answers have indicated, you need to use an anonymous type.
    As far as syntax is concerned, I personally far prefer method chaining. The method chaining equivalent would be:-

    var employee = _db.EMPLOYEEs
    .Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo)
    .Select(x => new { x.EMAIL, x.ID });

    AFAIK, the declarative LINQ syntax is converted to a method call chain similar to this when it is compiled.
    If you want the entire object, then you just have to omit the call to Select(), i.e.

    var employee = _db.EMPLOYEEs
    .Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo);

    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]

  • #769081
    You can use given example to get multiple column value in linq query
    var employee =  (from res in _db.EMPLOYEEs
    where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
    select new {email=res.EMAIL, username=res.USERNAME} );


  • Sign In to post your comments