2017-02-24 60 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