[英]How To Convert IEnumerable To one object
在我的应用程序中,用户可以具有多个角色,我想将角色列表转换为一个通用角色对象以申请许可
我如何处理将List转换为Common角色?
public class Role
{
public boolData ListBools { get; set; }
public ListId ListIds { get; set; }
}
public class boolData
{
public bool CanSale { get; set; }
public bool CanBuy { get; set; }
}
public class ListId
{
public IEnumerable<Int64> Product { get; set; }
public IEnumerable<Int64> Formula { get; set; }
}
例如,此用户有两个我要行使的角色,这些角色是一个角色对象共有的
IEnumerable<Role> UserRoles = new List<Role>()
{
new Role(){ListBools = new boolData()
{
CanBuy = false,
CanSale = true
},
ListIds = new ListId()
{
Product = new List<long>(){1,4,58},
Formula = new List<long>(){2,7,}
}
},
new Role(){ListBools = new boolData()
{
CanBuy = true,
CanSale = true
},
ListIds = new ListId()
{
Product = new List<long>(){1,6,70},
Formula = new List<long>(){2,9,}
}
},
};
必须转换为
Role Result = new Role()
{
ListBools = new boolData()
{
CanBuy = true,
CanSale = true
},
ListIds = new ListId()
{
Product = new List<long>() { 1, 4, 6, 58, 70 },
Formula = new List<long>() { 2, 7, 9, }
}
};
您可以使用Linq
的Any
和SelectMany()
组合,
喜欢,
var Result = new Role()
{
ListBools = new boolData()
{
CanBuy = UserRoles.Any(x => x.ListBools.CanBuy),
CanSale = UserRoles.Any(x => x.ListBools.CanSale)
},
ListIds = new ListId()
{
Product = UserRoles.SelectMany(x => x.ListIds.Product).Distinct(),
Formula = UserRoles.SelectMany(x => x.ListIds.Formula).Distinct()
}
};
有关公式和产品的列表,可以使用SelectMany + Distinct:
Role sum = new Role
{
ListBools = new boolData()
{
CanBuy = true,
CanSale = true
},
ListIds = new ListId
{
Formula = UserRoles.SelectMany(x => x.ListIds.Formula).Distinct().ToList(),
Product = UserRoles.SelectMany(x => x.ListIds.Product).Distinct().ToList()
}
};
我不知道如何生产ListBools
....也许您应该将所有规则分组并按boolData加入Formula / Product
您可以使用以下代码:
顺便说一句-我同意以下说法,即“类别/属性”名称可以是
var products = UserRoles.SelectMany(m => m.ListIds.Product).Distinct().OrderBy(m => m).ToList();
var formulas = UserRoles.SelectMany(m => m.ListIds.Formula).Distinct().OrderBy(m => m).ToList();
var anyCanBuy = UserRoles.Any(m => m.ListBools.CanBuy);
var anyCanSale = UserRoles.Any(m => m.ListBools.CanSale);
Role Result = new Role()
{
ListBools = new boolData()
{
CanBuy = anyCanBuy,
CanSale = anyCanSale,
},
ListIds = new ListId()
{
Product = products,
Formula = formulas,
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.