IEnumerable<T> 具有流畅验证的 GroupBy

IEnumerable<T> GroupBy with Fluent Validation

所以我要解决的问题是我使用了很多带有 <T> 的通用 classes 需要执行 .NET Async REST 调用来检索 IEnumerable<T> 来自 API 的对象列表。在 运行 时间,T 的东西很好地解决了,因为我在链上有一些具体的实例。

我有一个工人class:

public class Worker<T> where T : class, new()

有一个 REST 客户端工厂:

IBatchClientFactory batchClientFactory

在那个工厂中基本上创建了一个这样的实例:

public class BatchClient<T> where T : class, new()

那个BatchClient有一个重要的方法:

public BaseBatchResponse<T> RetrieveManyAsync(int top = 100, int skip = 0)

因此工作人员 class 的方法会执行如下操作:

var batchClient = this.batchClientFactory.Create<T>(siteId);
var batchResponse = await batchClient.RetrieveManyAsync(top, skip);

批量响应看起来像:

public class BaseBatchResponse<T>
{
    public List<T> Value { get; set; }

    public BaseBatchResponse<T> Combine(BaseBatchResponse<T> baseBatchResponse)
    {
        return new BaseBatchResponse<T>
        {
            Value = this.Value.Concat(baseBatchResponse.Value).ToList()
        };
    }
}

现在在 运行 时间一切正常,因为链的更高层我会将 Worker 实例化为类似的东西。 new Worker<Appointment>(); T 将完美地工作,因为链下的一切都只是做仿制药。

我现在的问题是我想评估我的 batchResponse 并浏览列表,运行 对列表中的每个元素进行一些验证。我看到 this article on stack overflow 似乎可以让您通过 Dictionary 使用 GroupBy 将列表拆分为 2 个列表,其中一些 SomeProp 是您要拆分的东西..但是您可以使用方法调用来执行 GroupBy 逻辑吗?更重要的是,我可以使用 FluentValidation 作为该方法调用吗?理想情况下,我的代码如下所示:

var groups = allValues.GroupBy(val => validationService.Validate(val)).ToDictionary(g => g.Key, g => g.ToList());
List<T> valids = groups[true];
List<T> invalids= groups[false];

其中结果将是我的有效对象列表和第二个无效对象列表。

理想情况下,我会做一个 FluentValidation class 绑定到我的 concreate Appointment class 并且里面有一个规则:

this.When(x => !string.IsNullOrWhiteSpace(x.Description), () => 
            this.RuleFor(x => x.Description).Length(1, 4000));

这会将所有内容挂钩在一起并用于确定我的对象在 运行时间是否属于有效或无效列表

我不确定流利的意思,有一种方法可以使用 LINQ 实现:

using System.Collections.Generic;
using System.Linq;

namespace Investigate.Samples.Linq
{
    class Program
    {
        public class SomeEntity
        {
            public string Description { get; set; }
        }

        static void Main(string[] args)
        {
            //Mock some entities
            List<SomeEntity> someEntities = new List<SomeEntity>()
            {
                new SomeEntity() { Description = "" },
                new SomeEntity() { Description = "1" },
                new SomeEntity() { Description = "I am good" },
            };

            //Linq: Where to filter out invalids, then category to result with  ToDictionary
            Dictionary<bool, SomeEntity> filteredAndVlidated = someEntities.Where(p => !string.IsNullOrWhiteSpace(p.Description)).ToDictionary(p => (p.Description.Length > 1));

            /* Output:
             *  False: new SomeEntity() { Description = "1" }
             *  True: new SomeEntity() { Description = "I am good" }
             * */
        }
    }
}

代码段:

Dictionary<bool, SomeEntity> filteredAndVlidated = someEntities.Where(p => !string.IsNullOrWhiteSpace(p.Description)).ToDictionary(p => (p.Description.Length > 1));