简体   繁体   English

如何在C#中向linq select new命令的结果中添加项目?

[英]how to add items to result of a linq select new command in C#?

in C# using linq i have a query like: 在使用linq的C#中,我有一个查询,例如:

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? 我该怎么办?

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 }; 

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
    }

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 编辑:您可以为您的结果集创建一个容器类,然后基于该容器类进行选择:类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);
  }

您可以执行以下操作:

var result = from p in cart select new { p.Product.Title, p.Product.Price, Weight = 55, Message ="message" };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM