首页 > 解决方案 > 我怎样才能用 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; }
}

标签: c#linq

解决方案


检查这段代码是否符合您的要求

// 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

推荐阅读