如何解决如何使用linq在C#中将列表转换为字典?
我有如下数据
var listOfForm= new List<FormType>()
{
new FormType() { Page = 1,Type = "FORM-K4"},new FormType() { Page = 2,Type = "OTHER-FORM"},new FormType() { Page = 3,new FormType() { Page = 4,Type = "FORM-K5"},new FormType() { Page = 5,new FormType() { Page = 6,new FormType() { Page = 7,new FormType() { Page = 8,Type = "FORM-K6"},new FormType() { Page = 9,Type = "OTHER_FORM"},new FormType() { Page = 10,Type = "FORM-K7"},new FormType() { Page = 11,new FormType() { Page = 12,};
我想创建一个字典。我想将FORM-K4之后的这两个OTHER-FORM添加到字典中,其中的键是FORM-K4,列表的其余部分具有相同的模式,将OTHER-FORM添加到之前检测到的类型/键中。 / p>
例如,在form-k5之后有三个Other-form,因此我想将每个Page表单将这些other-form添加到form-k5键中。
var dictForm = dictionary<Type,List<Page>>
所以当我访问dictForm.key form-k5时,它将返回值4,5,6,7,而键是form-k4时,则返回值1,2,3。
解决方法
您可以创建自己的扩展方法以将数据转换为字典,因为它具有自定义规则。
代码
public static class EnumerableExtensions
{
public static Dictionary<string,List<int>> ToDictionary(this IEnumerable<FormType> formTypes)
{
Dictionary<string,List<int>> output = new Dictionary<string,List<int>>();
string currentType = string.Empty;
foreach (var formType in formTypes)
{
if (formType.Type.StartsWith("FORM") && formType.Type != currentType)
{
currentType = formType.Type;
if (!output.ContainsKey(currentType))
{
output.Add(currentType,new List<int>());
}
}
output[currentType].Add(formType.Page);
}
return output;
}
}
用法
Dictionary<string,List<int>> output = listOfForm
.ToDictionary();
输出
FORM-K4 : 1,2,3
FORM-K5 : 4,5,6,7
FORM-K6 : 8,9
FORM-K7 : 10,11,12
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。