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
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.
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.
So Lambda expression is the best for development over LINQ queries.
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[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With