c# - Linq Group Object
问题描述
I have a list of customer objects where I am having trouble understanding how to properly group this into a new object.
public class CustomerOrders
{
public string CustomerId { get; set; }
public string OrderType { get; set; }
public DateTime OrderDate { get; set; }
public string Account { get; set; }
public decimal Amount { get; set; }
public string ClientId { get; set; }
}
I need to have a new object list to access with the CustomerOrders grouped by:
CustomerId
OrderType
OrderDate
List of Account, Amount and ClientId as these repeat for the CustomerId, OrderType and OrderDate
Also is there a way to add a few null properties where I can populate later through an iteration to this new list for example "Approved" to the Grouped fields?
解决方案
这是实现此目的的一种方法。如果这个类是一个实体,并且 account、amount 和 clientid 是另一个表中可以连接到客户数据的字段,那就更好了。
下面是我来自 linqpad 的示例。
void Main()
{
List<CustomerOrders> orders = new List<CustomerOrders>() {
new CustomerOrders() {CustomerId = "1", OrderType = "1", OrderDate = DateTime.Now, Account = "1234", Amount = 2.2M, ClientId = "asdf"},
new CustomerOrders() {CustomerId = "1", OrderType = "1", OrderDate = DateTime.Now, Account = "1235", Amount = 5.3M, ClientId = "hjkl"},
new CustomerOrders() {CustomerId = "2", OrderType = "3", OrderDate = DateTime.Now, Account = "1236", Amount = 6.2M, ClientId = "zxcv"}
};
var data =
from o in orders
group new { o.CustomerId, o.OrderType, o.OrderDate } by new { o.CustomerId, o.OrderType, o.OrderDate } into grouped
select new Results {
CustomerId = grouped.First().CustomerId,
OrderType = grouped.First().OrderType,
OrderDate = grouped.First().OrderDate,
Data =
orders.Where(x =>
x.CustomerId == grouped.First().CustomerId &&
x.OrderType == grouped.First().OrderType &&
x.OrderDate == grouped.First().OrderDate
).Select(d => new CustomerOrderData {
Account = d.Account,
Amount = d.Amount,
ClientId = d.ClientId
})
};
data.Dump();
}
public class CustomerOrders
{
public string CustomerId { get; set; }
public string OrderType { get; set; }
public DateTime OrderDate { get; set; }
public string Account { get; set; }
public decimal Amount { get; set; }
public string ClientId { get; set; }
}
public class CustomerOrderData {
public string Account { get; set; }
public decimal Amount { get; set; }
public string ClientId { get; set; }
}
public class Results
{
public string CustomerId { get; set; }
public string OrderType { get; set; }
public DateTime OrderDate { get; set; }
public bool? Approved { get; set; } // adding null property
public IEnumerable<CustomerOrderData> Data { get; set; }
}
推荐阅读
- javascript - Google Script 对 JSON 嵌套数组进行排序
- reactjs - 通过从后端检查更改状态并保持状态
- vba - 如何使用 Chrome 浏览器通过 VBA 抓取 Twitter?
- javascript - 如何检索数据库中的特定字段信息?
- c# - 将超链接添加到 Excel 工作表 closedxml
- tensorflow - Keras中非常奇怪的Reshape层行为
- python - pandas根据行上的唯一值返回索引值
- javascript - 旋转后如何获得正确的屏幕内部宽度?
- python - 队列中的异步共享变量
- javascript - 使用 twitter API js 流式传输用户的推文