简体   繁体   English

将属性添加到列表中的项目

[英]Add property to an item in a list

So I'm just starting out with ASP.NET MVC, and I've run into an issue I just can't find an answer to. 所以我刚开始使用ASP.NET MVC,但是遇到了一个我找不到答案的问题。

I'm grabbing some data from an SQL database, and send it to the view with this code: 我从SQL数据库中获取一些数据,并使用以下代码将其发送到视图:

var listingsQuery = (from s in db.tblListings select s).OrderBy(s => s.listingID).Skip(100).Take(25);
var listings = listingsQuery.ToList();

return View(listings);

This works great, but I want to add a value in the list of results. 这很好用,但是我想在结果列表中添加一个值。 Basically what I'm trying to do is something like this: 基本上我想做的是这样的:

foreach (var item in listings)
{
    this.Add("propertyType", "Home");
}

But obviously that doesn't work. 但这显然行不通。 I've tried doing ToArray() instead of ToList() and that got me nowhere. 我试图做ToArray()而不是ToList(),这让我无处可去。

Do you want to add a new property to each object in the List collection? 是否要向List集合中的每个对象添加新属性? If so, you can create a new type that inherits from whatever object type is in the list (hover over the listingsQuery variable - the type is inside the <> symbols) and add the new property to it: 如果是这样,您可以创建一个继承自列表中任何对象类型的新类型(将鼠标悬停在listingsQuery变量上-该类型位于<>符号内),然后向其中添加新属性:

public class MyNewType : ExistingTableType
{
    public string PropertyType { get; set; }
}

Then inside of your query, project the properties into this new type: 然后在查询中,将属性投影到此新类型中:

var listingsQuery = (from s in db.tblListings  
                     orderby s.listingID
                     select new NewType
                     {
                         listingID = s.listingID,
                         someOtherField = s.someOtherField
                     }
                    ).Skip(100).Take(25);

Now you can cycle through each record and assign a value: 现在,您可以循环浏览每条记录并分配一个值:

foreach(var record in listings)
{
   record.ProperyType = "Home";
}

There are other ways of doing this as well (assuming you're using EF), for example, if you used raw SQL you can cast the result type directly into the new type (without having the map each field), but this should get you started. 还有其他方法也可以执行此操作(例如,假设您使用的是EF),例如,如果您使用的是原始SQL,则可以将结果类型直接转换为新类型(无需在每个字段中都具有映射),但这应该可以你开始了。

If you want to add a new row to your listings collection you need to do listings.Add instead of this.Add 如果要向清单集合添加新行,则需要进行清单。添加而不是此。添加

If you want to modify a value in your listing collection then you need to do 如果要修改列表集中的值,则需要执行

     foreach(var item in listings)
     {
       item.PropertyName = value;
     }

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

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