Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
2.00/5 (3 votes)
See more:
C#
//How to get the price of a certain product from the list? Example the Ipad. How can I get the price and return the value in a label.


//My Class

public class ProductInfo

    {
       string _name;
       string _location;
       double _price;

    public ProductInfo(string name, string location, double price)
    {
       _name = name;
       _location = location;
       _price = price;
    }


 public string Name{ get; set}

 public string Location{ get; set}

 public double Price{ get; set}

}
}
//This is my List
    List<ProductInfo> Product = new List< ProductInfo >();

            Product.Add(new ProductInfo ("Ipad", "USA", 585.56));
            Product.Add(new ProductInfo ("Laptop", "USA", 1227.75));
            Product.Add(new ProductInfo ("MemoryCard", "USA", 32.77));
            Product.Add(new ProductInfo ("Mouse", "USA", 56.19));
            Product.Add(new ProductInfo ("HardDisk", "USA", 165.50));
            Product.Add(new ProductInfo ("Monitor", "USA", 286.90,));
Posted
Comments
Clifford Nelson 25-Mar-12 20:30pm    
I voted 4 since this gave an opportunity to have many people respond.

Here is a cleaner solution:
C#
var price = Products.FirstOrDefault(i => i.Name = productName).Select(i => i.price);


In good design, there should not be a case where you get a null back, and if you do, it should probably be an exception. This is probably an exception because there is a bug somewhere in the code. An exception can be caught with the above code with a try catch block. But if you want a default then use Linq properly:

C#
var price = Products.FirstOrDefault(i => i.Name = productName).Select(i => i i == null ? 0 : i.price);
 
Share this answer
 
v3
Comments
ProEnggSoft 25-Mar-12 0:56am    
It's good. +5 for the idea.
I have some comments please my see solution (5)
ProEnggSoft 25-Mar-12 20:26pm    
I have seen the modification done in my answer. But, please indicate what you have modified, if you have edited others answer.
Further, I have up voted your answer. Whereas it seems you have down voted my answers. Thank you.
Clifford Nelson 25-Mar-12 20:29pm    
I have an issue with you response as stated above. I would hope that the design would not lookup a price when there is no such produce. This is an exception.
ProEnggSoft 25-Mar-12 20:41pm    
Please see my comment to your response above. Thank you.
Clifford Nelson 25-Mar-12 21:12pm    
As noted in my response to your responce.
The FirstOrDefault extension method of IEnumerable interface returns the first occurance or the default value of the collection member.
C#
var price = Products.FirstOrDefault(i => i.Name = productName).Select(i => i.price);

In this case it returns the ProductInfo object.
The ProductInfo class does not have Select method Hence, the .Select will throw error in the above statement.
So, instead of .Select(i => i.price) we have to use .Price.
ProductName is a string, = in i.Name = productName is to be == for comparison

But, when the List is empty the FirstOrDefault returns null as the default value for a reference type is null and if the required product is not found say we passed Ipad2, the method returns null. In either case if we directly access Price property on the object returned by the FindOrDefault method, there is a chance of error. Hence, I think the better option would be
C#
ProductInfo selectedProductInfo = Products.FirstOrDefault(p => p.Name == productName);
double price = selectedProductInfo == null ? 0 : selectedProductInfo.Price;


[EDIT]The following text inserted by Clifford Nelson[EDIT]
May not have an issue with null, and can cover with an exception. During debug can put an Debug.Asser. Can also do the following

var price = (Products.FirstOrDefault(i => i.Name = productName) ?? new Preduct()).Select(i => i.price);
 
Share this answer
 
v4
Comments
Shahin Khorshidnia 25-Mar-12 5:52am    
Good answer
ProEnggSoft 25-Mar-12 6:25am    
Thank you
Member 8714846 25-Mar-12 11:46am    
Awesome..
ProEnggSoft 25-Mar-12 12:00pm    
Thank you.
Clifford Nelson 25-Mar-12 20:27pm    
Why not just include the second line in the LINQ statement??? Plus, if you do not find the value, that might be an exception. When should be get far enough to be looking up a price when you have the name. Sound like a serious design problem and an exception should be raised anyway. Plus you can continue in LINQ, why not continue in LINQ! Otherwise why even bother with LINQ in the first place. I have further improved the answer after some thought.
Hello

First thing.

Your class must defined like this:
C#
public class ProductInfo
{
    //string _name;
    //string _location;
    //double _price;

    public ProductInfo(string name, string location, double price)
    {
        Name = name;
        Location = location;
        Price = price;
    }


    public string Name { get; set; }

    public string Location { get; set; }

    public double Price { get; set; }
}


If you realy want full properties, then:
C#
public class ProductInfo
{
    public ProductInfo(string name, string location, double price)
    {
        Name = name;
        Location = location;
        Price = price;
    }

    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    private string _location;
    public string Location
    {
        get { return _location; }
        set { _location = value; }
    }

    private double _price;
    public double Price
    {
        get { return _price; }
        set { _price = value; }
    }
}



Then for getting the price:

C#
var prices = Product.Where(p => p.Name == "Mouse").Select(p => p.Price);
double price;
if (prices.Count() > 0)
    price = prices.First();
 
Share this answer
 
v4
Comments
Member 8714846 24-Mar-12 22:11pm    
It won't return the value.
Shahin Khorshidnia 25-Mar-12 5:37am    
It will.
You must adjust the Class.
The class had a problem and I've adjusted it.

In the Constructor of productInfo you are initializing the fields (_name, _price, _location) but you must initialize the properties. (Name, Price, Location)
By the way my solution (with my difined class) is working here and I'm sure it's working for you.
[no name] 24-Mar-12 23:04pm    
5
Shahin Khorshidnia 25-Mar-12 5:28am    
Thanks Wes.
ProEnggSoft 25-Mar-12 1:12am    
+5
The solution 1 given by Shahin Khorshidnia is correct, only thing is he has used the method syntax of LINQ. The Query syntax of LINQ is easy to read, as given below

C#
List<ProductInfo> Products = new List< ProductInfo >() {
            new ProductInfo ("Ipad", "USA", 585.56),
            new ProductInfo ("Laptop", "USA", 1227.75),
            new ProductInfo ("MemoryCard", "USA", 32.77),
            new ProductInfo ("Mouse", "USA", 56.19),
            new ProductInfo ("HardDisk", "USA", 165.50),
            new ProductInfo ("Monitor", "USA", 286.90)};

//I have used StringComparison.InvariantCultureIgnoreCase to safeguard against the comparison of characters 
//English characters when other culture is current culture. 
//However other options can be used as per your requirement
var selectedProductPrices = from product in Products
                        where product.Name.Equals("Ipad", StringComparison.InvariantCultureIgnoreCase)
                        select product.Price;
double selectedProductPrice =  selectedProductPrices.Count() > 0 ? selectedProductPrices.First() : 0;


As he pointed out when Auto Implemented properties are used there is no need of back end store.
Further, I suggest to use plural for List objects i.e. instead of Product say Products, this gives more clarity while working with the code.
 
Share this answer
 
v2
Comments
Shahin Khorshidnia 25-Mar-12 5:32am    
Thanks. My +5
ProEnggSoft 25-Mar-12 5:37am    
Thank you.
At the simplest, you can run a loop and retrieve the item you are looking for.
For r.g.
C#
foreach (ProductInfo o in Product)
{
    if (o.Name == "Ipad")
    {
       MessageBox.Show(o.Price.ToString());
    }
}
 
Share this answer
 
Comments
Shahin Khorshidnia 25-Mar-12 5:43am    
foreach has a better performance than LINQ, I tested it;) but Linq is more clear, shorter and if it be used correctly and timly, somethimes it is able to have a better performance.

My +4 to your solution
Of course in this way, it needs a break too.
foreach (ProductInfo o in Product)
{
if (o.Name == "Ipad")
{
MessageBox.Show(o.Price.ToString());
break;
}
}
Abhinav S 25-Mar-12 22:14pm    
Fair point about the break statement. Thanks.
Shahin Khorshidnia 25-Mar-12 22:22pm    
You're welcome ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900