角色迭代及去重
#region 根据用户编码获取该层级角色信息以及该层级以下角色信息的迭代接口... /// <summary> /// 根据用户角色编码获取该层级角色以及该层级以下角色的信息... /// </summary> /// <param name="code">用户编码。</param> /// <returns>可迭代的角色信息的集合。</returns> public IEnumerable<Security_Role> GetIEnumerableRoleByCode(string code) { try { using (SecurityEntities securityEntities = new SecurityEntities()) { var roleInfo = from s in securityEntities.Security_Role where s.PedigreeCode == code select s; return roleInfo.ToList().Concat(roleInfo.ToList().SelectMany(t=> GetIEnumerableRoleByCode(t.Code))); } } catch (Exception ee) { //写入异常日志表。 //抛出异常。 throw ee; } } #endregion #region 根据用户角色列表获取该列表中层级角色信息以及该层级以下角色信息... /// <summary> /// 根据用户角色列表获取该列表中层级角色信息以及该层级以下角色信息... /// </summary> /// <param name="listUserRole">用户角色列表。</param> /// <returns>角色信息实体列表。</returns> public List<RoleInfo> GetRoleInfoByListRole(List<RoleInfo> listUserRole) { List<RoleInfo> roleInfoList = new List<RoleInfo>(); foreach (var lur in listUserRole) { foreach (var gir in GetIEnumerableRoleByCode(lur.PedigreeCode)) { RoleInfo roleInfo = new RoleInfo(); roleInfo.ID = gir.ID; roleInfo.Name = gir.Name; roleInfo.Code = gir.Code; roleInfo.PedigreeCode = gir.PedigreeCode; roleInfo.Enable = gir.Enable;
//添加当前角色的下属角色
roleInfoList.Add(roleInfo);
}
//添加当前角色
roleInfoList.Add(lur);
}
return RemoveDuplicate(roleInfoList); } #endregion #region /// <summary> /// 去除用户角色列表中的重复项。 /// </summary> /// <param name="listUserRole">用户角色列表。</param> /// <returns>不重复的用户角色列表项。</returns>
public List<RoleInfo> removeDuplicate(List<RoleInfo> listUserRole) { var roleInfoList = listUserRole.Distinct(new RoleInfoCpmpare());
//或者roleInfoList.Distinct(new EqualCompare<RoleInfo>((x, y) => (x != null && y != null) && (x.Code == y.Code))).OrderBy(z => z.PedigreeCode).ThenBy(o => o.Code).ToList();
return roleInfoList.ToList();
}
#endregion
#region
/// <summary>
/// 用户角色列表重复项对比类。继承泛型接口
/// </summary>
public class RoleInfoCpmpare : IEqualityComparer<RoleInfo>
{
#region IEqualityComparer<RoleInfo> 成员
public bool Equals(RoleInfo x, RoleInfo y)
{
if (x.Code == y.Code)
return true;
else
return false;
}
public int GetHashCode(RoleInfo obj)
{
return 0;
}
#endregion
}
#endregion