c# - 当父母相同时如何分组列出孩子
问题描述
我有一个Business
看起来像这样的列表(Company
:list parent;Item
:list children)
Business
--------
CompanyA
TaxRate
Item1
Name
Price
Total
Item2
Name
Price
Total
Month
CompanyB
TaxRate
Item3
Name
Price
Total
Item4
Name
Price
Total
Month
CompanyA
TaxRate
Item5
Name
Price
Total
Item6
Name
Price
Total
Month
我想Company
按TaxRate
这个分组
Business
--------
CompanyA
TaxRate
Item1
Name
Price
Total
Item2
Name
Price
Total
Item5
Name
Price
Total
Item6
Name
Price
Total
Month
CompanyB
TaxRate
Item3
Name
Price
Total
Item4
Name
Price
Total
Month
我希望有人会在这种情况下帮助我
解决方案
这是我发现完成任务的最佳方式:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Diagnostics;
using System.Data;
namespace ConsoleApplication45
{
class Program
{
static void Main(string[] args)
{
List<Business> companies = new List<Business>() {
new Business() { name = "CompanyA",items = new List<Item>(){ new Item() { name = "Item1"}, new Item() { name = "Item2"}}},
new Business() { name = "CompanyB", items = new List<Item>() { new Item() { name = "Item3"}, new Item() { name = "Item4"}}},
new Business() { name = "CompanyA",items = new List<Item>(){ new Item() { name = "Item5"}, new Item() { name = "Item6"}}},
};
var groups = companies.GroupBy(x => x.name).Select(x => new { business = x.FirstOrDefault(), items = x.SelectMany(y => y.items) });
List<Business> newCompanies = new List<Business>();
foreach (var group in groups)
{
Business company = group.business;
company.items = group.items.ToList();
newCompanies.Add(company);
}
}
}
public class Business
{
public string name { get; set; }
public List<Item> items { get; set; }
public decimal taxrate { get; set; }
public string month { get; set; }
}
public class Item
{
public string name { get;set;}
public decimal price { get;set;}
public decimal total { get;set;}
}
}
推荐阅读
- json - 我们可以在没有循环的情况下在 oracle 中获得列表属性的总和吗?
- java - 两个应用程序需要不同的 JDK
- neural-network - 在 CNN 的第一层中,过滤器如何在 RGB 图像中运行?
- c# - 在 DataContext C# WPF 之外使用绑定的 CheckBox 值
- r - R:我的数据框有 2 列,每行都有一串数字,有没有办法拆分字符串并添加每列的值?
- fipy - 如何将参数“underRelaxation”设置为耦合方程?
- php - 在 laravel 的一个地方编写公共关系,并在需要的模型中扩展该类
- filter - “权重”这个词是指适合 CNN 中卷积滤波器的值吗?
- flutter - 颤动图像轮播更改边框半径
- sql - Apache骆驼没有在sql更新上映射设置参数