21

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

Mark
  • 4,773
  • 8
  • 53
  • 91

4 Answers4

32

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[].

NinjaFart
  • 1,626
  • 1
  • 20
  • 24
scartag
  • 17,548
  • 3
  • 48
  • 52
  • The return get's an error, that says: Cant convert expression type Namstring, Pricestring to return type string[] – Mark Aug 10 '14 at 16:53
  • @Mark i'm not sure you have the right return type for the solution you are seeking. You might consider returning dynamic if you aren't interested in creating a type for it. A type would provide more clarity though. – scartag Aug 10 '14 at 17:00
  • @scaretag, would you be able to provide an example of this based on my updated question? – Mark Aug 10 '14 at 17:03
  • @Mark i've done that already. i've updated my answer with an example. – scartag Aug 10 '14 at 17:03
  • `OrderBy(x => x)` will not work, if the class doesn't implement `IComparable` interface in the `NamePriceModel` class. Or OP have to order by some column. – Farhad Jabiyev Aug 10 '14 at 18:00
  • @FarhadJabiyev Thanks .. i've edited it to order by Id. Although I suspect that the OP would have made that change already. – scartag Aug 10 '14 at 18:07
  • @scartag You will not beleive, but he asked a new question about this error. :) [Here it is](http://stackoverflow.com/questions/25231394/c-sharp-linq-query-keeps-hitting-catch) – Farhad Jabiyev Aug 10 '14 at 18:15
12

You can use:

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

And here is YourClass implementation:

public class YourClass
{
  public string Name {get; set;}
  public int ID {get; set;}
  public int Price {get; set;}
}

And your AllProducts method's return type must be YourClass[].

Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
7

using LINQ and Lamba, i wanted to return two field values and assign it to single entity object field;

as Name = Fname + " " + LName;

See my below code which is working as expected; hope this is useful;

Myentity objMyEntity = new Myentity
{
id = obj.Id,
Name = contxt.Vendors.Where(v => v.PQS_ID == obj.Id).Select(v=> new { contact = v.Fname + " " + v.LName}).Single().contact
}

no need to declare the 'contact'

Muru Bakthavachalam
  • 1,340
  • 12
  • 8
2
        Object AccountObject = _dbContext.Accounts
                                   .Join(_dbContext.Users, acc => acc.AccountId, usr => usr.AccountId, (acc, usr) => new { acc, usr })
                                   .Where(x => x.usr.EmailAddress == key1)
                                   .Where(x => x.usr.Hash == key2)
                                   .Select(x => new { AccountId = x.acc.AccountId, Name = x.acc.Name })
                                   .SingleOrDefault();