c# – 如何使用Join和Where返回IList?

前端之家收集整理的这篇文章主要介绍了c# – 如何使用Join和Where返回IList?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使用 Linq或EF Join之类的东西在C#MVC中实现连接和位置?

这是我试图实现的等效sql.

select * from promotion P
JOIN PromotionsClaimed PC
on PC.PromotionId = P.objectid
where PC.userId = @USERID

方法应返回用户的促销列表.首先,我获得所有促销的列表,然后我获得用户声明的促销的综合列表.这就是我到目前为止所拥有的.

public IList<Promotion> GetRewardsForUser(string userId)
    {
        //a list of all available promotions
        IList<Promotion> promos =  _promotionLogic.Retrieve();

        //contains a list of Promotion.objectIds for that user
        IList<PromotionsClaimed> promosClaimed = _promotionsClaimedLogic.RetrieveByCriteria(t => t.userId == userId);

        //should return a list of the Promotion name and code for the rewards claimed by user,but a complete list of Promotion entities would be fine
        var selectedPromos =
            from promo in promos
            join promoClaimed in promosClaimed on promo.objectId equals promoClaimed.PromotionId
            select new { PromoName = promo.Name,PromoCode = promo.Code };

        return selectedPromos;
    }

我意识到这里有很多问题.我正在尝试学习Linq和Entity Framework,但我不知道如何将where子句添加到IList中,或者是否有更简单的方法来实现它.

在我看来,有一种方法可以过滤促销列表,其中包含promosClaimed列表中的Promotion.objectId,但我不知道语法.

解决方法

public IList<Promotion> GetRewardsForUser(string userId)
{
    //a list of all available promotions
    IList<Promotion> promos =  _promotionLogic.Retrieve();

    //contains a list of Promotion.objectIds for that user
    IList<PromotionsClaimed> promosClaimed = _promotionsClaimedLogic.RetrieveByCriteria(t => t.userId == userId);

    //should return a list of the Promotion name and code for the rewards claimed by user,but a complete list of Promotion entities would be fine
    var selectedPromos =
        (from promo in promos
        join promoClaimed in promosClaimed on promo.objectId equals promoClaimed.PromotionId
        select new { PromoName = promo.Name,PromoCode = promo.Code }).ToList();

    return selectedPromos;
}

猜你在找的C#相关文章