通过另一个列表<object2> C#LINQ过滤列表<object>

时间:2015-05-31 16:26:50

标签: c# linq

请考虑以下列表:

class user {
   public int id {get; set;}
   public string name {get; set;}
   public bool selected {get; set;} 
}

class coupon {
   public string username {get; set;}
   public string coupontype {get; set;}
   public string code {get; set;}
}

List<user> lUser = new List<user>();
List<coupon> lCoupon = new List<coupon>();

如何(LINQ)使用lCoupon过滤lUser,以便剩下的唯一值是lCoupon.username字段中存在lUser.name字段的值} lUser.selectedtrue

伪代码:

lCoupon = lCoupon.Where (w => lUser.name == w.name AND lUser.selected == true).ToList();

2 个答案:

答案 0 :(得分:5)

您可以在Any列表中使用LINQ lUser方法,如:

var coupons = lCoupon
    .Where(c => lUser.Any(u => u.selected && u.name == c.username))
    .ToList();

答案 1 :(得分:4)

您也可以使用加入来执行此操作:

var coupons = from coupon in lCoupons
          join user in lUser on coupon.username equals user.name
          where user.selected
          select coupon; 

通过这种方式,您可以轻松地从两种对象类型中选择值,例如:

var selectedObjects = from coupon in lCoupons
          join user in lUser on coupon.username equals user.name
          where user.selected
          select new { CouponCode = coupon.code, UserId = user.Id} ; 

如果您愿意,可以ToList()