如何将GroupBy与ICollections一起使用?

时间:2015-05-15 07:35:58

标签: c# linq

我使用GroupBy对像这样的对象进行分组:

    SELECT TOP 1
            t.Id ,
            t.OId ,
            t.Amount ,
    t.DUserId,
            t.StartDate ,
            t.ExtDesc,
    t.StatusId
    FROM    dbo.[Transaction] t
            JOIN dbo.Wallet cw ON t.CId = cw.Id
            JOIN dbo.Wallet dw ON t.DId = dw.Id
    WHERE   ExtKey = @ExtKey 
            AND ( cw.vId = @vId 
                  OR dw.VId = @vId 
                )

--Second Selct which executes twice with differenc params


    SELECT  u.Id ,
            UserName ,
            PinCode ,
            CurrencyId ,
            StatusId ,
            PersonalNumber ,
            gu.DefaultVendorServiceId ,
            CountryId,
    u.FirstName,
    u.LastName
    FROM    dbo.[User] u
            LEFT JOIN dbo.GamblerUser gu ON gu.UserId = u.Id
    WHERE   u.Id = @UserId


--Last select with (updlock)


SELECT w.Id, AccountNo, FundTypeId, VendorServiceId, Balance, UserId, vs.IsLocalAccount

FROM Wallet w (UPDLOCK)
JOIN VendorService vs on w.VId = vs.Id
WHERE 
    w.UserId  = @UserId
AND w.FundTypeId = @FundTypeId 
AND w.VendorServiceId  = @VendorServiceId


-- Insert


    INSERT  INTO [dbo].[Transaction]
            ( StartDate ,
              OTypeId ,
              StatusId ,
              Amount ,
              ExtDesc,
              DUserId 
            )
    VALUES                  ( @StartDate ,
              @OTypeId ,
              @StatusId ,
              @Amount ,
              @ExtDesc,
              @DUserId 
            )

    SET @Id = ( SELECT  @@IDENTITY
              )


-- Update on updlocked table    


UPDATE dbo.Wallet SET

    Balance = ISNULL(@Balance, Balance)

WHERE Id = @Id

一切正常。
但现在我想将Specialized为ICollection<>。的对象分组 例如:

var categories=
    tovRDb.MyObjects.AsEnumerable().Where(t => myHashSet.Contains(t.Id))
                      .GroupBy(t => t.Specialization, t => t,
                               (key, g) => new {Name = key.Name, CategoryItems = g.ToList()})
                      .OrderBy(t => string.IsNullOrEmpty(t.Name))
                      .ThenBy(t => t.Name)
                      .ToList();

分组后:

MyObject1: "Berlay's Meat"
Specializations{Chicken, Pork, Beef}

MyObject2: "Wonday's Chickery"
Specializations{Chicken}


MyObject3: "Rooki's Meat"
Specializations{Chicken, Pork}

有任何建议吗?

1 个答案:

答案 0 :(得分:2)

categories为:

var categories = tovRDb.MyObjects.AsEnumerable().Where(t => myHashSet.Contains(t.Id));

var catsGrouped = categories.SelectMany(
    x => x.Specializations, // Specializations is an IEnumerable<Specialization>
    (x, y) => new
    {
        Category = x,
        Specialization = y,
    }).GroupBy(x => x.Specialization, x => x.Category)
    .ToArray();

我使用SelectMany来&#34;乘以&#34;每个类别的专业化......然后我按Specialization重新分组结果。结果是IGrouping<Specialization, MyObject>[]