请考虑以下列表:
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.selected
为true
?
伪代码:
lCoupon = lCoupon.Where (w => lUser.name == w.name AND lUser.selected == true).ToList();
答案 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()
。