我有一个存储库类,其中包含一个列表,其中包含在我的网站上填写表单的人,如果他们将参加我的聚会.我使用GetAllRespones读取值,并使用AddResponse(通过接口)向列表中添加值
现在我想检查某人是否已填写我的表单,如果是,我想检查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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,我在"attend.WillAttend"收到错误消息
错误是:bool不包含WillAttend的定义,并且没有扩展方法'WillAttend'接受类型bool的第一个参数可以找到
任何人都可以帮我解决我的代码吗?:)
问题出在这里:
var attend =
responses.Any(x => x.Email == response.Email && x.WillAttend == response.WillAttend);
Run Code Online (Sandbox Code Playgroud)
Any<>()回报bool.bool没有财产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;
Run Code Online (Sandbox Code Playgroud)
如果您想要使用指定条件的许多响应Where():
var attend = responses.Where(x => x.Email == response.Email && x.WillAttend != response.WillAttend);
if (attend.Any())
{
//do something
}
Run Code Online (Sandbox Code Playgroud)
此外,您可以使您的方法更简单:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
278 次 |
| 最近记录: |