2017-02-24 64 views
1

我有一個存儲庫類,其中包含一個列表,其中包含填寫表單的人員列表,如果他們將出席我的派對。 我讀與GetAllRespones價值觀和我添加值與AddResponse名單(通過接口)在c#中更新列表#

現在我要檢查是否有人已經填充了我的形式,如果是我要檢查,如果WillAttend的值更改並更新它。

我可以看到我做了什麼下面這裏

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using PartyInvites.Abstract; 

namespace PartyInvites.Models 
{ 
public class GuestResponseRepository : IRepository 

{ 
    private static List<GuestResponse> responses = new List<GuestResponse>(); 

    IEnumerable<GuestResponse> IRepository.GetAllResponses() 
    { 
     return responses; 
    } 

    bool IRepository.AddResponse(GuestResponse response) 
    { 
     bool exists = responses.Any(x => x.Email == response.Email); 
     bool existsWillAttend = responses.Any(x => x.WillAttend == response.WillAttend); 

     if (exists == true) 
     { 
      if (existsWillAttend == true) 
      { 
       return false; 
      } 

      var attend = responses.Any(x => x.Email == response.Email && x.WillAttend == response.WillAttend); 
      attend.WillAttend = response.WillAttend; 
      return true; 

     } 

     responses.Add(response); 
     return true; 
    } 
} 
} 

的問題是,我在「attend.WillAttend」

錯誤是得到一個錯誤信息:BOOL不包含定義WillAttend並具有 沒有擴展方法「WillAttend」接受 bool類型的第一個參數可以發現

任何人都可以幫我解決我的代碼? :)

回答

7

的問題是在這裏:

var attend = 
     responses.Any(x => x.Email == response.Email && x.WillAttend == response.WillAttend); 

Any<>()回報boolbool沒有財產WillAttend。如果你想獲得的第一反應與x => x.Email == response.Email && x.WillAttend == response.WillAttend使用First()(或FirstOrDefault()但在你的情況下,你總是會至少有一個元素,所以只需使用First()):

var attend = responses.First(x => x.Email == response.Email && x.WillAttend != response.WillAttend); 
attend.WillAttend = response.WillAttend; 

如果你想與特定的條件使用Where()許多答覆:

var attend = responses.Where(x => x.Email == response.Email && x.WillAttend != response.WillAttend); 

if (attend.Any()) 
{ 
    //do something 
} 

此外,您還可以讓你的方法更簡單:

bool IRepository.AddResponse(GuestResponse response) 
{ 
    if (responses.Any(x => x.Email == response.Email)) //here 
    { 
     if (responses.Any(x => x.WillAttend != response.WillAttend)) //here 
     { 
      return false; 
     } 

     var attend = responses.First(x => x.Email == response.Email && x.WillAttend != response.WillAttend); 
     attend.WillAttend = response.WillAttend;   
     return true; 
    } 

    responses.Add(response); 
    return true; 
} 
+0

謝謝你的快速回復!實現了你建議的代碼,但由於某種原因,var參數一直爲空。有關於此的任何想法? – valheru

+0

@valheru,你有'NullReferenceException'或看到使用調試器的值? –

+0

按照TamásSzabó的建議,用x.WillAttend!= response.WillAttend修復它,現在它工作正常。非常感謝您的幫助! – valheru

2

responses.Any(...)返回一個布爾值(無論responses是否包含您指定的值)。您將有實際得到的是價值與

responses.First(<lambda expression you specified>) 

例如和對象上得到WillAttend

+0

謝謝你做到了!以後發生的其他問題 – valheru

+0

是什麼?也許我可以幫忙。 –

+0

var參數保持爲'null' – valheru