IEnumerable <t> GroupBy通过流畅的验证

时间:2019-01-10 23:54:01

标签: c# linq generics ienumerable fluentvalidation

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

我有一个工人班:

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)

,以便工人类的方法执行以下操作:

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类,该类绑定到我的concreate Appointment类并在其中具有规则:

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

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

1 个答案:

答案 0 :(得分:1)

我不确定流利的方法,可以使用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));