C# 中的List类型,对支持Linq,更方便我们去操作数据按照我们的需求去转换。以下是在开发过程中,我所用到的几种方法。
先定义List类:
public class onecrm_goods_stock
{
/// <summary>
/// 库存id
/// </summary>
public long stock_id { get; set; }
/// <summary>
/// 商品id
/// </summary>
public long goods_id { get; set; }
/// <summary>
/// 商品数量
/// </summary>
public int goods_num { get; set; }
/// <summary>
/// 销售额_计数
/// </summary>
public int sale_count { get; set; }
}
public class order_goods_data
{
public long goods_id { get; set; }
public int goods_num { get; set; }
}
1、去重单项
//获取去重商品id,Key是去重项
List<long> goods_id = data.GroupBy(u => u.goods_id)
.Select(grp => (long)grp.Key).ToList();
2、去重单项,操作其他项
//用group by 对商品id去重,获取总数量
List<order_goods_data> goods = data.GroupBy(u => u.goods_id)
.Select(t => new order_goods_data {
goods_id = t.Key,
goods_num = t.Sum(a => a.goods_num)
}).ToList();
3、将List转换为string[]
List<string> openidlist = user.GroupBy(u => u.openid)
.Select(grp => grp.Key).ToList();
string[] openidtag = openidlist.Skip(1).Take(50).ToArray();