首页 > 解决方案 > 如何在添加之前检查对象列表中是否已经存在具有相同 ID 的对象?

问题描述

我现在正在学习 C#,我正在尝试制作一个对象列表。在将对象添加到列表之前,我想检查列表中是否已经存在具有相同 id 的对象。(我不能有 2 个具有相同“id”的“商品”对象。)

这是代码(刚刚意识到我用法语命名了每个变量、类和方法。希望它仍然可以理解):

using System;
using System.Collections.Generic;

public class Program
{
    class Marchandise
    {
        private int _id; // attribute I need to check in every object before adding
        public int Id{get; set;} 

        private double _poids;
        public double Poids{get; set;}

        private double _volume;
        public double Volume{get; set;}

        public Marchandise( int id, double poids, double volume)
        {
            this._id = id;
            this._poids = poids;
            this._volume = volume;
        }   
    }

    class Transport
    {
        public double _distance;
        List<Marchandise> _listeMarchandise = new List<Marchandise>();

        public void Ajout(Marchandise marchandise)
        {
            // add function with duplicate check for ID     
        }
    }

    public static void Main()
    {
        Marchandise m1 = new Marchandise(20,27.6,89.2); //test code
        Marchandise m2 = new Marchandise(20,10.2,5.1);
        Transport t1 = new Transport();
        t1.Ajout(m1);
        t1.Ajout(m2);

    }
}

标签: c#

解决方案


您可以使用 LINQ 方法Any()检查是否存在满足特定条件的对象。在您的情况下,您检查是否存在具有此类 ID 的对象。你可以像这样使用它:

class Transport
{
    public double _distance;
    List<Marchandise> _listeMarchandise = new List<Marchandise>();

    public void Ajout(Marchandise marchandise)
    {
        if (_listeMarchandise.Any(it => it.Id == marchandise.Id)) {
            // it already exists, do something about it.
        }
        // add fonction with duplicate check for ID     
    }
}

推荐阅读