Gopal Sharma Gopal Sharma - 3 months ago 9
C# Question

Select and Match Data from List using LINQ C#

I have data in List, and i want to do login if data matches with any of records.

public HttpResponseMessage Post(form model)
{
List<form> user = new List<form>();
user.Add(new form { username = "admin", password = "admin" });
user.Add(new form { username = "Gopal", password = "123" });
user.Add(new form { username = "niit", password = "niit" });

if (model.username == user.Select(p => p.username.Equals(model.username))
{

}
}


I want to like this - (Done with Hard coded data)

if (model.username == "admin" && model.password == "admin")
{
return Request.CreateResponse(HttpStatusCode.Accepted);
}
else { return Request.CreateResponse(HttpStatusCode.InternalServerError); }


This is my Model Class - Form

public class form
{
[Required]
public string username { get; set; }
[Required]
public string password { get; set; }
}


I have done this with hard coded data but want to do with list. Please help me this out. How Can I do it?

Answer

Try this way

 if (user.Where(a => a.username == model.username && a.password == model.password).Select(p => p).Count() != 0)
    {
        return Request.CreateResponse(HttpStatusCode.Accepted);
    }
    else 
    { 
       return Request.CreateResponse(HttpStatusCode.InternalServerError);
    }

or you can simply use any

 if (user.Any( a => a.username.Contains(model.username) && a.password.Contains(model.password)))
   {
       return Request.CreateResponse(HttpStatusCode.Accepted);
   }
   else 
   { 
      return Request.CreateResponse(HttpStatusCode.InternalServerError);
   }