Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting multiple columns with linq query and lambda expression

Tags:

c#

sql

asp.net

linq

I'm new to C# ASP.NET, and am working on my first application.

I'm trying to create a linq statment that return an arrary.

I have a table of products. I want to be able to select name, id, and price, for each product where the status == 1.

I am struggling with crating a way to do this. I have only been able to return individual items/columns. I have been stuck on this wayyy to long.

This is what I have so far:

try
{
  using (UserDataDataContext db = new UserDataDataContext())
  {
    return db.mrobProducts.Select(x => x.Name).OrderBy(x => x).ToArray();
  }
}

If you look in the screen shot below, you can see I have 2 errors, Select = Type object can not be refered from it's usage ToArray = cant resolve symbol to array

enter image description here

like image 694
Mark Avatar asked Aug 10 '14 16:08

Mark


People also ask

How do you select two columns in LINQ?

Select multiple columns using Entity Framework You can select to an anonymous type, for example... var dataset2 = (from recordset in entities. processlists where recordset. ProcessName == processname select new { serverName = recordset.

Can you use lambda expression instead of LINQ query?

So performance-wise, there's no difference whatsoever between the two. Which one you should use is mostly personal preference, many people prefer lambda expressions because they're shorter and more concise, but personally I prefer the query syntax having worked extensively with SQL.

Which is faster LINQ or lambda?

So Lambda expression is the best for development over LINQ queries.


1 Answers

Not sure what you table structure is like but see below.

public NamePriceModel[] AllProducts()
{
    try
    {
        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();
         }
     }
     catch
     {
         return null;
     }
 }

This would return an array of type anonymous with the members you require.

Update:

Create a new class.

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

I've modified the query above to return this as well and you should change your method from returning string[] to returning NamePriceModel[].

like image 98
scartag Avatar answered Oct 15 '22 01:10

scartag