我有一个存储库类,其中包含一个列表,其中包含在我的网站上填写表格的人是否会参加我的聚会。
我使用 GetAllRespones 读取值,并使用 AddResponse 将值添加到列表中(通过接口(interface))
现在我想检查是否有人已经填写了我的表格,如果是,我想检查 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”收到一条错误消息
the error is: bool does not contain definition for WillAttend and has no extension method 'WillAttend' accepting a first argument of type bool could be found
谁能帮我修复我的代码? :)
最佳答案
问题在这里:
var attend =
responses.Any(x => x.Email == response.Email && x.WillAttend == response.WillAttend);
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;
如果您想要许多具有指定条件的响应,请使用
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;
}
关于c# - 在 C# 中更新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42441231/