如何在Linq查询中聚合字符串列表?

时间:2014-02-22 15:10:52

标签: c# linq

我需要最终使我的MVC表中的列具有一串OrderNumbers。我似乎无法弄清楚必须有

的集合
public IEnumerable<OrderShippedListModel> GetRecentShippedOrders(string authenticatedUsername)
{
    User currentUser = new User().GetUser(authenticatedUsername);
    Order (from r in dc.Orders
            where r.Location.OrganizationID == currentUser.OrganizationID
            && r.CloseDate != null
            && r.ProductShipDate != null
            orderby r.LastModifiedDate descending
            select new OrderShippedListModel
            {
                ID = r.ID,
                OrderNumbers = r.Processes.Select(p=>p.OrderNumber),  //This needs to aggregate to a string
                Label = r.Label,
                Location = r.Location.Label,
                CreateDate = r.CreateDate,
                ProductShipDate = r.ProductShipDate,
                LastModifiedDate = r.LastModifiedDate,
                CloseDate = r.CloseDate
            }).Take(3);
}

这是我的班级模特

public class OrderShippedListModel
{
    public int ID { get; set; }

    public string Label { get; set; }

    public string Location { get; set; }

    [Display(Name = "Create Date")]
    public DateTime CreateDate { get; set; }

    [Display(Name = "Last Modified Date")]
    public DateTime LastModifiedDate { get; set; }

    [Display(Name = "Product Ship Date")]
    public DateTime? ProductShipDate { get; set; }

    [Display(Name = "Close Date")]
    public DateTime? CloseDate { get; set; }

    [Display(Name = "Job Numbers")]
    public string OrderNumbers { get; set; }
}

2 个答案:

答案 0 :(得分:3)

使用string.Join

OrderNumbers = string.Join("", r.Processes.Select(p=>p.OrderNumber)),

答案 1 :(得分:0)

另一个是聚合:

var s = r.Processes.Aggregate((accum, elem) => accum += elem.OrderNumber)