简体   繁体   English

如何使用C#检查列表中是否存在值

[英]How can I check if a value exists in a list using C#

I have the following code that gives me a list of id and names from the new ASP.NET MVC5 Identity: 我有以下代码,它给我一个新的ASP.NET MVC5标识中的id和名称列表:

        var identityStore = new IdentityStore();
        var users =
          (
              from user in identityStore.DbContext.Set<User>()
              select new
              {
                  id = user.Id,
                  name = user.UserName
              }
          );

How could I modify this so that it allows me to check if a UserName exists? 我怎么能修改它,以便它允许我检查UserName是否存在?

Here's the user class: 这是用户类:

public class User : IUser
{
    public User();
    public User(string userName);

    [Key]
    public string Id { get; set; }
    public virtual ICollection<UserLogin> Logins { get; set; }
    public virtual UserManagement Management { get; set; }
    public virtual ICollection<UserRole> Roles { get; set; }
    public string UserName { get; set; }
}
if(identityStore.DbContext.Set<User>().Any(u => UserName == "yourUserName"))
{
    // user exists
}
else
{
    // user does not exist
}

Does it fit for your requirements? 它符合您的要求吗? Your question is bit unclear. 你的问题有点不清楚。

You can query the username with a where statement if this is what you want, eg 如果这是你想要的,你可以使用where语句查询用户名,例如

var users = from user in identityStore.DbContext.Set<User>()
            where user.UserName != null && !user.UserName.Equals(string.Empty)
            select ...

anyways, it is a possible duplicate of this answer LINQ syntax where string value is not null or empty 无论如何,它是这个答案LINQ语法的可能重复, 其中字符串值不为null或为空

string.IsNullOrEmpty does work only in some cases, so be careful! string.IsNullOrEmpty仅在某些情况下有效,所以要小心!

Or if you just look for a specific user name, simply query for it 或者,如果您只是查找特定的用户名,只需查询它即可

var users = from user in identityStore.DbContext.Set<User>()
            where user.UserName.Equals("whatever")
            select ...

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

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