c# - 如何在添加之前检查对象列表中是否已经存在具有相同 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);
}
}
解决方案
您可以使用 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
}
}
推荐阅读
- emacs - 将 flycheck 与 compile_commands.json 一起使用
- rxjs - Rxjs - refCount 变为 0 后出现意外的 publishReplay + refCount 行为
- android-studio - java.lang.RuntimeException:编译时无法启动活动 ComponentInfo,“,”附近的语法错误
- android - Android Studio Cmake构建错误:向量类型之间的无效转换
- php - MyBB find_replace_templatesets 不工作
- python - Python写入文件使用不必要的存储?
- java - 为什么我的循环在计算最后一个数字之前就跳出来了?
- unit-testing - 酶:wrapper.find('SickButton').simulate('click') 没有点击
- regex - 谷歌表格:正则提取
- sql-server - 在 BeginTrans 之后立即 CommitTrans