首页 > 解决方案 > 使用 LINQ 检查时即时更新记录

问题描述

我想检查我的 IEnumerable 列表是否包含某些内容并即时更新它。

我现在在做什么:

private bool IsPointValid(Point point, IEnumerable<CustomRectangle> rectangles)
{
    return rectangles.Any(r => r.Rectangle.Contains(point) && !r.IsChecked);
}

我的代码正确检查了所有内容,但我的问题是,如何IsChecked在完成整体检查后更改值,以便下次调用函数时,IsChecked值会正确更新。

标签: c#linq

解决方案


从你的问题看来你想要这样的东西,

假设您有一个对象列表(例如 Demo 类)

public class Demo
{
    public string Name;
    public bool flag;
    public Demo(string Name, bool flag)
    {
        this.Name = Name;
        this.flag = flag;
    }
}

并且您正在检查此列表是否包含一些具有特定值的元素并更新其他值。

List<Demo> list = new List<Demo>();
list.Add(new Demo("amit", false));

//Note here we are also setting x.flag to true with checking conditions 
if(list.Any(x => x.Name == "amit"  && !x.flag && (x.flag = true)))
{

}

在这里,一旦流进入 if,标志将设置为 true。

编辑

如果列表中可能有多个条目满足相同的条件(检查条件),上面的代码将只更新其中的第一个。如果您想更新所有这些,请执行以下代码。

//here too we are setting flag to true, 
//but for all those objects which satisfy conditions
if(list.Where(x => x.Name == "amit" && !x.flag).Select(y => (y.flag=true)).Count() > 0)
{

}

推荐阅读