简体   繁体   English

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

[英]Filter a list<object> by another list<object2> C# LINQ

Consider following lists: 请考虑以下列表:

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>();

How is it possible (with LINQ ) to filter lCoupon with lUser so that the only values that remain are those with lCoupon.username field present in lUser.name , with lUser.selected being true ? 这怎么可能(与LINQ )来过滤lCouponlUser使仍然存在的唯一价值是那些lCoupon.username出现在现场lUser.name ,与lUser.selectedtrue

Pseudo code: 伪代码:

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

You could use the LINQ Any method on the lUser list, as in: 您可以在lUser列表中使用LINQ Any方法,如下所示:

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

You can also do this with a join: 您也可以通过加入执行此操作:

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

This way you can easely select values from both object types, eg: 这样,您可以从两种对象类型中轻松选择值,例如:

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} ; 

You can ToList() this if you prefer. 如果您愿意,可以使用ToList()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM