2016-08-07 1 views
0

リストにデータがあり、データがいずれかのレコードと一致する場合はログインを行います。LINQを使用してリストからデータを選択して一致させるC#

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)) 
      { 

      } 
     } 

私はこれが好きにしたい - フォーム

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

私は、ハードコーディングされたデータが、でこれを行っている -

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

これは私のモデルクラスである(ハードコーディングされたデータで完了)リストとやりたいこれを手伝ってください。どうすればいいですか?

答えて

1

私は、これは、生産コードではありません願っていますこのよう

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); 
    } 

か、単に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); 
    } 
+0

ありがとうございます。 –

+0

素晴らしい、幸せなコーディング – Mostafiz

1

を使用することができますしてみてください!そのユーザーデータが格納されている場合は、パスワードのsalting + hashingを使用したいと思うでしょう。あなたが経験していない場合は、この種のもので独自のコードを書かないことをお勧めします。

は、しかし、あなたの質問に答えるために、あなたが最も可能性が高いこれが欲しい:

よりよいデータ構造はいえあり
user.Any(u => u.username == model.username && u.password == model.password) 

。たとえば、ディクショナリでは、コレクション全体を反復処理するのではなく、ユーザー名(フォーム?)のO(1)検索をユーザー名で行うことができます。あなたがこれを行うことができます

+0

それは簡単な答えです。ありがとう。できます。 –

1

、次のコード

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

このようになります 'user.Any(use => model.username.Contains(use.username)&& model.password.Contains(use.password))' –

+0

はい、それは私が投稿したいくつかの変更を加えることによって動作しますコメント。どうもありがとう..!! –

+0

@GopalSharma upvoteにご存じですか? – Sajeetharan

0

用途:

if (user.Where(x=> x.username.Equals(model.username) && x.password.Equals(model.password)).FirstOrDefault() != null) 
     { 
      return Request.CreateResponse(HttpStatusCode.Accepted); 
     } 
     else { return Request.CreateResponse(HttpStatusCode.InternalServerError); } 

は、それはあなたを助けることを願っています。

関連する問題