C# List操作合集

        C# 中的List类型,对支持Linq,更方便我们去操作数据按照我们的需求去转换。以下是在开发过程中,我所用到的几种方法。

先定义List类:

    public class onecrm_goods_stock
    {
        /// 
        /// 库存id
        /// 
        public long stock_id { get; set; }

        /// 
        /// 商品id
        /// 
        public long goods_id { get; set; }

        /// 
        /// 商品数量
        /// 
        public int goods_num { get; set; }

        /// 
        /// 销售额_计数
        /// 
        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 goods_id = data.GroupBy(u => u.goods_id)
    .Select(grp => (long)grp.Key).ToList();

2、去重单项,操作其他项

//用group by 对商品id去重,获取总数量
List 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 openidlist = user.GroupBy(u => u.openid)
      .Select(grp => grp.Key).ToList();

string[] openidtag = openidlist.Skip(1).Take(50).ToArray();

你可能感兴趣的:(C#,c#)