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

4
  • I could not manage to put a where clause in, it would create an error, no matter where or how I was able to add it, Commented Aug 10, 2014 at 16:54
  • return a 2 dimensional arrary?? Commented Aug 10, 2014 at 16:59
  • @GrantWinney, I've updated the question, as I have been implmenting everyones answer, and am still having issues here,,, Commented Aug 10, 2014 at 17:02
  • 1
    Change string[] to Tuple<int, string, string> Commented Aug 10, 2014 at 17:03

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

7 Comments

The return get's an error, that says: Cant convert expression type Namstring, Pricestring to return type string[]
@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.
@scaretag, would you be able to provide an example of this based on my updated question?
@Mark i've done that already. i've updated my answer with an example.
OrderBy(x => x) will not work, if the class doesn't implement IComparable<T> interface in the NamePriceModel class. Or OP have to order by some column.
|
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[].

1 Comment

thanks for the answer . worked for me.optimized query.
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'

Comments

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();

2 Comments

could you please Elaborate a Little on your proposed Code?
Here Accounts and User tables are connected by AccountId foreign key. where condition applied on user table columns .We are selecting two columns from Accounts Table

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.