c# - 我怎样才能用 linq 改进这个?
问题描述
我有这段代码:
foreach(var planning in Planning)
{
if (onlyOneMatrice)
{
if (idMatrice == null || planning.IDMatrice == idMatrice)
{
idMatrice = planning.IDMatrice;
}
else
{
onlyOneMatrice = false;
}
}
else
{
idMatrice = null;
_ErrorMatrice = $"Error";
}
}
}
谁丑。我正在尝试使用 Linq 来减少它,但我一定是在某个地方弄错了。有我的测试:
bool IsMonoOrEmptyMatrice()
{
var id = Planning.FirstOrDefault(x=> { return x.IDMatrice != null});
return id==null || Planning.All( x => { return x.IDMatrice == null || x.IDMatrice == id});
}
但它每次都返回null。
我有一个 observableCollection“Planning”,每个对象都包含一个“idMatrice”数据。我要检查的是列表中的所有 idMatrices 是否相同。
示例:对于您正在扫描的对象“A”,所有矩阵必须相同。如果找到两个不同的矩阵,我会返回一条错误消息。
我还想到了类似的东西:
Planning.Distinct().Count() > 1 ? "somethingHere" : null ;
如果有人有建议.....提前谢谢你
编辑:计划对象:
public partial class Planning
{
public System.DateTime Jour { get; set; }
public string Matricule { get; set; }
public Nullable<int> Cycle { get; set; }
public string Type_Jour { get; set; }
public Nullable<System.DateTime> Heure_début1 { get; set; }
public Nullable<System.DateTime> Heure_fin1 { get; set; }
public string Type_Prise1 { get; set; }
public string IDEtablissement1 { get; set; }
public string IDSection1 { get; set; }
public Nullable<int> Couleur1 { get; set; }
public bool Visible1 { get; set; }
public string Type_Durée { get; set; }
public string IDEtablissement_Durée { get; set; }
public string IDSection_Durée { get; set; }
public string IDService_Durée { get; set; }
public Nullable<System.DateTime> Date_MAJ { get; set; }
public string IDMatrice { get; set; }
}
解决方案
检查这段代码是否符合您的要求
// check if any IdMatrice is null
if(Planning.Any(p => p.IDMatrice == null))
//return error
if(Planning.GroupBy(p => p.IDMatrice).Count() > 1)
// list is not identical
else
// list is identical
推荐阅读
- javascript - 尝试修复删除或添加广告时计数错误的 CGI 广告轮播脚本
- hash - 尝试操纵 SHA-256 算法的初始状态时出现问题
- c++ - 实现依赖类型
- javascript - 使用 axios (Vue 3) 接收的本地 JSON 中的搜索列表
- macos - Homebrew:如何列出最后安装的 N 个软件包?
- docker - Docker exec 命令创建文件
- php - 如何获取 PHP 单个数组值
- spring-boot - 通过 feign 调用将多个多部分文件从一个 Spring Boot 微服务传输到另一个
- amazon-web-services - 使用来自不同云 vps 的 s3 支持连接到 aws 存储网关(比如 digitalocean)
- java - JavaFX根据里面的VBox改变GridPane Row的高度