【发布时间】:2020-01-02 01:58:21
【问题描述】:
所以我试图将ErrorItem 的列表分组到ValidationFormatErrorDTO 的列表中,具体取决于FieldType 或ValidationFormat。
我们的目标是拥有一个只包含一种错误类型的ValidationFormatErrorDTO 列表。
最终对象。所以我试图列出它:
public class ValidationFormatErrorDTO
{
public ValidationFormat ValidationFormat { get; set; }
public FieldType FieldType { get; set; }
public List<ValidationFormatErrorItemDTO> ErrorItems { get; set; }
}
public class ValidationFormatErrorItemDTO
{
public int LineNumber { get; set; }
public string LineValue { get; set; }
}
错误对象示例:
示例 1:
var error = new ErrorItem
{
LineNumber = 2,
LineValue = "Test",
FieldType = FieldType.DateTime,
ValidationFormat = null
};
示例 2:
error = new ErrorItem
{
LineNumber = 11,
LineValue = "john.doe.test.com",
ValidationFormat = ValidationFormat.Email,
FieldType = null
};
示例 3:
error = new ErrorItem
{
LineNumber = 32,
LineValue = "1212",
ValidationFormat = ValidationFormat.PhoneNumber,
FieldType = null
};
从这里我被卡住了。
我试过了:
var test = tempListErrors.GroupBy(x => x.ValidationFormat)
.Select(y => new ValidationFormatErrorDTO
{
ValidationFormat = y.Key,
ErrorItems = ??
}).ToList();
但首先这意味着我应该对基于 FieldType 的错误执行相同的操作。这会给我 2 个 ValidationFormatErrorDTO 列表,我将不得不加入 1 个列表。
其次,使用这种方法,我遇到了IGrouping<ValidationFormat, ErrorItem>,我不知道该如何处理。
你们中的任何一个人都在考虑如何从我现在的位置来做这件事,或者考虑一个更好的解决方案,那太棒了!
感谢您的宝贵时间!
编辑:
所以,根据@Ashkan 的回答,我会这样:
var formatErrors = tempListErrors.GroupBy(x => x.ValidationFormat)
.Select(y => new ValidationFormatErrorDTO
{
ValidationFormat = y.Key,
ErrorItems = y.Select(x => new ValidationFormatErrorItemDTO
{
LineNumber = x.LineNumber,
LineValue = x.LineValue
}).ToList()
}).ToList();
var fieldTypeErrors = tempListErrors.GroupBy(x => x.FieldType)
.Select(y => new ValidationFormatErrorDTO
{
FieldType = y.Key,
ErrorItems = y.Select(x => new ValidationFormatErrorItemDTO
{
LineNumber = x.LineNumber,
LineValue = x.LineValue
}).ToList()
}).ToList();
关于我现在如何合并这两者有什么想法吗?
或者如何同时按ValidationFormat 和FieldType 分组以获得一个列表?
像这样?
var both = tempListErrors.GroupBy(x => new { x.ValidationFormat, x.FieldType })
.Select(y => new ValidationFormatErrorDTO
{
ValidationFormat = y.Key.ValidationFormat,
FieldType = y.Key.FieldType,
ErrorItems = y.Select(x => new ValidationFormatErrorItemDTO
{
LineNumber = x.LineNumber,
LineValue = x.LineValue
}).ToList()
}).ToList();
【问题讨论】:
-
最后一个 sn-p 就是你要找的。span>