过滤后从两个列表中选择列

时间:2016-06-22 14:11:33

标签: c# linq

我目前有以下Linq查询:

from cache

这意味着首先检查参数列表以确保提供者列表中存在客户端guid。然后,它将ClientGuids分组到参数列表中,并选择clientGuid和min StartDate。

我遇到的问题是我还需要从提供者列表中选择一些列,例如UserName。我到底该怎么做?是否可以在1个linq语句中执行此操作,或者我是否必须在2个单独的语句中执行此操作?

    var clientsToPull =
        parameters.Where(x => providers.Select(y => x.ClientGuid).Contains(x.ClientGuid))
            .GroupBy(x => x.ClientGuid)
            .Select(y => new ClientsToPull { ClientGuid = y.Key, StartDate = y.Min(c => c.FromDate)});

1 个答案:

答案 0 :(得分:1)

您可以在一个语句中执行此操作,使用Joinparametersproviders以及两者的项目信息进行匹配。 e.g ...

var providers = new List<Providers>()
{
    new Providers() { ClientGuid = Guid.NewGuid(), UserName = "A", Password = "B" },
    new Providers() { ClientGuid = Guid.NewGuid(), UserName = "B", Password = "C" },
};

var parameters = new List<Parameters>()
{
    new Parameters() { ClientGuid = providers.First().ClientGuid, StartDate = "C" },
    new Parameters() { ClientGuid = providers.First().ClientGuid, StartDate = "B" },
    new Parameters() { ClientGuid = providers.Take(2).Last().ClientGuid, StartDate = "Tomorrow!" },
    new Parameters() { ClientGuid = Guid.NewGuid(), StartDate = "Last year" },
};

var result = parameters
    .GroupBy(a => a.ClientGuid, a => a)
    .Join(
        providers,
        parameterGroup => parameterGroup.Key,
        provider => provider.ClientGuid,
        (parameterGroup, provider) => new { provider.ClientGuid, provider.UserName, MinStartDate = parameterGroup.Min(groupMember => groupMember.StartDate) });