public struct Unit { public List<Business> list; public float Subtotal; } public struct Business { public string ID; public string Currency; public float Amount; } public static IEnumerable<Unit> GetUnits() { var dataSource = new List<Business>(); var result = new Dictionary<KeyValuePair<string, string>, Unit>(); foreach (var b in dataSource) { var key = new KeyValuePair<string, string>(b.ID, b.Currency); if(!result.Keys.Contains(key)) { var unit = new Unit(); unit.list.Add(b); unit.Subtotal += b.Amount; result.Add(key, unit); } else { var unit = result[key]; unit.list.Add(b); unit.Subtotal += b.Amount; } } return result.Values; } 直接遍历就是了,如果一定要用linq,就只能添加一个字段用来区分小结行和原始数据行,看你数据量多大了,优化的空间还是有的。
你还是要LINQ直接查出来?那就加字段把小结行区分出来,我给你弄一下,效率未必比这个高
public struct Business { public string ID; public string Currency; public float Amount; public bool IsSubtotal; } public static IEnumerable<Business> GetUnits() { var dataSource = new List<Business>(); var test = from b in dataSource group b by new {b.ID, b.Currency} into g select new Business { ID = g.Key.ID, Currency = g.Key.Currency, Amount = g.Sum(i => i.Amount), IsSubtotal = true }; dataSource.AddRange(test.ToList()); dataSource.OrderBy(i => new {i.ID, i.Currency}); return dataSource; } 步骤1:手动修改Business类,加上一个字段,IsSubtotal 步骤2:查出小计再与源数据合并 步骤3:界面层根据IsSubtotal的值决定是否显示编号和币种。
{
public List<Business> list;
public float Subtotal;
} public struct Business
{
public string ID;
public string Currency;
public float Amount;
} public static IEnumerable<Unit> GetUnits()
{
var dataSource = new List<Business>();
var result = new Dictionary<KeyValuePair<string, string>, Unit>();
foreach (var b in dataSource)
{
var key = new KeyValuePair<string, string>(b.ID, b.Currency);
if(!result.Keys.Contains(key))
{
var unit = new Unit();
unit.list.Add(b);
unit.Subtotal += b.Amount;
result.Add(key, unit);
}
else
{
var unit = result[key];
unit.list.Add(b);
unit.Subtotal += b.Amount;
}
}
return result.Values;
}
直接遍历就是了,如果一定要用linq,就只能添加一个字段用来区分小结行和原始数据行,看你数据量多大了,优化的空间还是有的。
{
public string ID;
public string Currency;
public float Amount;
public bool IsSubtotal;
} public static IEnumerable<Business> GetUnits()
{
var dataSource = new List<Business>();
var test = from b in dataSource
group b by new {b.ID, b.Currency}
into g
select
new Business
{
ID = g.Key.ID,
Currency = g.Key.Currency,
Amount = g.Sum(i => i.Amount),
IsSubtotal = true
};
dataSource.AddRange(test.ToList());
dataSource.OrderBy(i => new {i.ID, i.Currency});
return dataSource;
}
步骤1:手动修改Business类,加上一个字段,IsSubtotal
步骤2:查出小计再与源数据合并
步骤3:界面层根据IsSubtotal的值决定是否显示编号和币种。