如何访问linq组结果

时间:2015-03-04 03:09:28

标签: c# linq

这可能看起来很傻但我花了足够的时间,我想我需要更多接触linq。

我有linq表达式导致一个组(key = int,list = string) 我想要的很简单。我想根据密钥将组列表分配给List<string>变量。

摘自sql,结果是一个小组

var productPerBranch =
    from i in 
    (
        from br in 
        (
            from pp in context.ProductPricings
            join p in productQuery on pp.ProductId equals p.ProductId
            where organizationRestrictedPartnerLocations.Contains(pp.PartnerLocationId)
            select new { pp.ProductId, pp.PartnerLocationId }
        )
        join pl in context.PartnerLocation on br.PartnerLocationId equals pl.PartnerLocationId into k
        from l in k.DefaultIfEmpty()
        select new { br.ProductId, l.DisplayName }
    )
    group i by i.ProductId into g
    select g;

例如,如果我想将带有Key = 0的列表分配给此变量 List <string> l我该怎么做?

1 个答案:

答案 0 :(得分:1)

试试这个:

var query =
(
    from br in 
    (
        from pp in context.ProductPricings
        join p in productQuery on pp.ProductId equals p.ProductId
        where organizationRestrictedPartnerLocations.Contains(pp.PartnerLocationId)
        select new { pp.ProductId, pp.PartnerLocationId }
    )
    join pl in context.PartnerLocation on br.PartnerLocationId equals pl.PartnerLocationId into k
    from l in k.DefaultIfEmpty()
    select new { br.ProductId, l.DisplayName }
).ToLookup(x => x.ProductId, x => x.DisplayName);

var result = query[0].ToList();