1

in C# using linq i have a query like:

var result = from p in cart select new { p.Product.Title, p.Product.Price };

now i want to add some another items to result. For example adding:

int weight;
string message;

so that i can have something like:

foreach( var r in result)
{
   dosomething(r.weight;)
   dosomething(r.message);
   dosomething(r.title);
   dosomething(r.price);
  }

is it possible? how should i do it?

John Sykor
  • 727
  • 5
  • 15
Amir Jalali
  • 3,132
  • 4
  • 33
  • 46

4 Answers4

7

You would need to create new items. Could you do something like this instead?

var result = from p in cart select new { Title = p.Product.Title,
                                         Price = p.Product.Price,
                                         Weight = 0,
                                         Message = null }; 
zimdanen
  • 5,508
  • 7
  • 44
  • 89
2

Select new create anonymous type so you cannot add the property once it get created but one thing you can do is create your own type and assign property value in query and than assign other property value later on..

//your class will be 
class MyClass
{
     float weight {get;set;}
     string Title {get;set;}
     float price {get;set;}
     string message {get;set;} 
}


   //select new will be     
    select new MyClass
    {
        Title =  p.Product.Title,
        price =  p.Product.Price,
        weight = 0,
        message = string.empty
    }
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1

You can't do that. Anonymous types are normal types and they are fixed at compile time. You can't change them later.


EDIT: You can create a container class for your result set and then select based on that: class MyResult

class MyResult
{
    public string Title { get; set; }
    public double Price { get; set; }
    public double Weight { get; set; }
    public string Message { get; set; }
}

And then you can use:

    var query = from t in cart
                select new MyResult
                {
                    Title = t.ProductTitle,
                    Price = t.Product.Price
                };

Later you could do:

foreach( var r in result)
{
   dosomething(r.Wight;)
   dosomething(r.Message);
   dosomething(r.Title);
   dosomething(r.Price);
  }
Habib
  • 219,104
  • 29
  • 407
  • 436
  • The @Zimdanen solution is great but i think it's better having a costume typed class. shouldn't be in foreach loop (var r in query)? – Amir Jalali Apr 27 '12 at 07:39
  • @cSharpper, yes for more readability you can have foreach(MyResult r in results), but var is sometimes as well, check out this thread its interesting http://stackoverflow.com/questions/236878/what-to-use-var-or-object-name-type – Habib Apr 27 '12 at 09:19
0

You can do the following :

var result = from p in cart select new { p.Product.Title, p.Product.Price, Weight = 55, Message ="message" };
aybe
  • 15,516
  • 9
  • 57
  • 105