Mohan Perera
Mohan Perera

Reputation: 370

Get values to each Label from a Method, which return as a List

I need to get values of ItemCode and ItemName into separate Labels using Linq. I implemented a query joining tblItem and tblInventry. It returns all rows as a List. Query is below,

public tblItem GetItemNameAndCode(int itemID)
{
    var iNameCode = from it in DB.tblItems
                    join inv in DB.tblInventories on it.ItemID equals inv.ItemID
                    where it.ItemID == itemID
                    orderby it.ItemName ascending
                    select it;
    return iNameCode.ToList<tblItem>();
}

From the above query(GetItemNameAndCode(ItemID)), I need to get ItemCode and ItemName(ascending). That code is below,

if (lblItemID != null)
{
      int ItemID = Convert.ToInt32(lblItemID.Text);
      this.ItemBO.Item = this.ItemBO.GetItemNameAndCode(ItemID);
      if (this.ItemBO.Item != null)
      {
          lblItemCode.Text = this.ItemBO.Item.ItemCode;
          lblItemName.Text = this.ItemBO.Item.ItemName;
      }
}

But how do I return only those 2 fields ? When I use this,

return iNameCode.ToList();

It gives an exception. Ultimately I need ItemName get ordered in ascending order.

Upvotes: 0

Views: 49

Answers (1)

Dan Dohotaru
Dan Dohotaru

Reputation: 3089

it's not very clear if you expect one result or many from the GetItemNameAndCode method, but based on

  • the name of the method
  • the return type
  • the usage afterwards

I presume you actually expect one single element having a code and a name property

In any case i would define an object to hold the return type

public class Shape
{
    public string Code { get; set; }
    public string Name { get; set; }
}

and refactor your method to return that one single element from the list

public Shape GetItemNameAndCode(int itemID)
{
    var query = from it in DB.tblItems
                join inv in DB.tblInventories on it.ItemID equals inv.ItemID
                where it.ItemID == itemID
                orderby it.ItemName ascending
                select new Shape
                {
                    Code = it.ItemCode,
                    Name = it.ItemName,
                };

    return query.SingleOrDefault();
}

notice the .SingleOrDefault() at the end

Upvotes: 1

Related Questions