gpt4 book ai didi

c# - 在 C# 中更新列表

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:54 25 4
gpt4 key购买 nike

我有一个存储库类,其中包含一个列表,其中包含在我的网站上填写表格的人是否会参加我的聚会。
我使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com