C# 从一个list中取出某一字段并去重生成一个新的list

public class AppointmentsDto
    {
        /// <summary>
        /// 资源ID
        /// </summary>
        public string ResourceID { get; set; }
        /// <summary>
        /// 部门ID
        /// </summary>
        public string DeptID { get; set; }
        /// <summary>
        /// 部门名称
        /// </summary>
        public string DeptName { get; set; }
    }
public class AppointmentsResourceDto
    {
        /// <summary>
        /// 资源ID
        /// </summary>
        public string ResourceID { get; set; }
    }

方法一:使用LinQ先对 AppointmentsDto对象列表中的ResourceID字段去重,然后转成AppointmentsResourceDto列表对象。

//查询列表
List<AppointmentsDto> lst = GetListByTable();
//获取AppointmentsResourceDto对象列表
List<AppointmentsResourceDto> obj = from e in lst.Select(o => o.ResourceID).Distinct() select new AppointmentsResourceDto { ResourceID = e };

 方法二:

//查询列表
List<AppointmentsDto> lst = GetListByTable();
//取得AppointmentsResourceDto对象列表
List<AppointmentsResourceDto> obj = lst.Select(o => o.ResourceID).Distinct().ToList().ConvertAll<AppointmentsResourceDto>(o => new AppointmentsResourceDto { ResourceID = o.ToString() });

这种方法一般可以用在日程,约会。例如:SchedulerControl控件的数据源。

步骤:用过一条SQL查出一个列表,作为SchedulerStorage的Appointments.DataSource。
然后从该列表中过滤去重取得一个新的列表作为SchedulerStorage的Resources.DataSource。

发布了36 篇原创文章 · 获赞 8 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_35351282/article/details/81532916