【问题标题】:Checking if an object is on the list I created [duplicate]检查对象是否在我创建的列表中[重复]
【发布时间】:2021-12-16 11:12:39
【问题描述】:

我正在制作一个注册多个参数的代码,然后检查这些参数是否已经在列表中,例如,我想检查一个电子邮件是否在这个列表中,我该怎么做检查?

List<Professional> lprofessional = new List<Professional>();

public int role_id = 1;
public string First_name { get; set; }
public string Last_name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Description { get; set; }

public Professional(int role_id, string firstname, string lastname, string email, string phone, string description) {
    this.First_name = firstname;
    this.Last_name = lastname;
    this.Email = email;
    this.Phone = phone;
    this.Description = description;
}

public void Create()
{
    Professional pro = new Professional(role_id, First_name, Last_name, Email, Phone, Description);
    if (lprofessional.Contains(email)//Here is the check maybe...
    {
        lprofessional.Add(pro);
        role_id++;
    }
}

【问题讨论】:

  • 您能添加构成列表的代码吗?
  • List lprofessional = new List();这个?
  • @GSerg 很遗憾没有,因为他想要一个指定的值,我想让程序检查用户输入的值是否与列表中的值相同
  • 有什么区别?

标签: c#


【解决方案1】:
if (lprofessional.Any(p => p.Email == email))
{
    // already in the list
}
else
{
    // not yet in the list
}

或者:

var p = lprofessional.FirstOrDefault(p => p.Email == email);
if (p is object)
{
    //already in the list, and you can use "p" to see or change other properties
}
else
{
    // not in the list
}

我知道还有使用模式匹配的更新选项可以用更少的代码做到这一点,但我还没有将模式匹配整合到我自己的工作流程中。

【讨论】:

    【解决方案2】:
    var email = "test@test.com";
    var listElement = lprofessional.Where(x=> x.Email.Equals(email)).FirstOrDefault();
        if(listElement != null)
        {
        //some code
         }
    

    var email = "test@test.com";
    var result = lprofessional.Any(x => x.Email.Equals(email));
    if( result) 
    {
    //some code here
    }
    

    【讨论】:

    • 您期望什么解决方案?
    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2018-07-17
    • 2017-11-26
    • 2021-08-06
    相关资源
    最近更新 更多