简体   繁体   English

如何编写 Linq 查询以检查列表是否具有该 ID

[英]How to write Linq query to check whether List have that id

I have a List inside that List one more List is there.我在该列表中有一个列表,还有一个列表。 How to check the id is present in any one of the List.如何检查id是否存在于任何列表中。

public class Users
{
    public virtual Userid { get; set; }
  
    public virtual List<UserCity> UserCities { get; set; }
}

And

public class UserCity
{
    public virtual UserCityId { get; set; }
  
    public virtual UserCityName { get; set; }
}

How to get the users which are having Userid =usercityid .如何获取拥有Userid =usercityidusers

Linq query i tried like this Linq 查询我试过这样

List<Users> lstusers = new List<Users>();
lstusers = lstusers
    .Where(x=>x.UserCity.Any(w => w.UserCityId == w.Userid ))
    .ToList();

If the users have usercityid with same userid i need to get those users .如果用户的usercityid具有相同的userid ,我需要获取这些users

There are some errors in your query.您的查询中有一些错误。 Try this:尝试这个:

// create a dummy list for testing
var lstusers = new List<Users>
{
   new Users {Userid = 1, UserCities = new List<UserCity>{ new UserCity { UserCityId = 1, UserCityName="xxx"} }  }
};
// execute the linq-query
lstusers = lstusers.Where(x => x.UserCities.Any(w => w.UserCityId == x.Userid)).ToList();
// and print the number of users found
Console.WriteLine($"Number of users found: {lstusers.Count}");

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

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