如何编写 Linq 查询来检查 List 是否具有该 id
How to write Linq query to check whether List have that id
我里面有一个列表,里面还有一个列表。如何检查 id
是否存在于任一列表中。
public class Users
{
public virtual Userid { get; set; }
public virtual List<UserCity> UserCities { get; set; }
}
和
public class UserCity
{
public virtual UserCityId { get; set; }
public virtual UserCityName { get; set; }
}
如何获得 users
有 Userid =usercityid
.
我试过这样的 Linq 查询
List<Users> lstusers = new List<Users>();
lstusers = lstusers
.Where(x=>x.UserCity.Any(w => w.UserCityId == w.Userid ))
.ToList();
如果用户有 usercityid
和相同的 userid
我需要得到那些 users
.
您的查询有一些错误。试试这个:
// 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}");
我里面有一个列表,里面还有一个列表。如何检查 id
是否存在于任一列表中。
public class Users
{
public virtual Userid { get; set; }
public virtual List<UserCity> UserCities { get; set; }
}
和
public class UserCity
{
public virtual UserCityId { get; set; }
public virtual UserCityName { get; set; }
}
如何获得 users
有 Userid =usercityid
.
我试过这样的 Linq 查询
List<Users> lstusers = new List<Users>();
lstusers = lstusers
.Where(x=>x.UserCity.Any(w => w.UserCityId == w.Userid ))
.ToList();
如果用户有 usercityid
和相同的 userid
我需要得到那些 users
.
您的查询有一些错误。试试这个:
// 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}");