我有一个存储库类,其中包含一个列表,该列表包含在他们的网站上填写表格的人员(无论他们是否参加我的聚会)。
我使用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;
    }
}
}


问题是,我在“ attend.WillAttend”处收到一条错误消息


  错误是:bool不包含WillAttend的定义,并且具有
  没有扩展方法'WillAttend'接受类型的第一个参数
  可以找到布尔


有人可以帮我解决我的代码吗? :)

最佳答案

问题在这里:

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;
}

关于c# - 更新C#中的列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42441231/

10-12 03:24