我不太喜欢C#和.NET。我遇到以下问题。
在我的代码中,我有这样的内容:
UOR uor;
foreach (int idUor in visibilitaPostRidistribuzioni)
{
uor = UorSQL.GetUorFromId(siglaAOO, idUor, dbConfig);
visibUtils.Uors.Add(uor);
}
其中visibUtils.Uors是UOR对象的列表。
如您所见,我正在迭代 ID 列表 (visibilitaPostRidistribuzioni)。对于每个 ID,我都会检索一个 UOR uor 对象,并将其添加到 visibUtils.Uors 列表中。
我需要的是一种智能方法,在插入之前检查此 uor 对象是否存在于 visibUtils.Uors 列表中,以避免重复。
如果两个 UOR 对象具有以下 2 个字段的相同值,则它们是同一对象:SiglaAOO 和 SiglaUOR
UOR 对象是一个模型类,如下所示:
public class UOR
{
private string unitaOperativaResponsabile;
public string UnitaOperativaResponsabile
{
get { return unitaOperativaResponsabile; }
set { unitaOperativaResponsabile = value; }
}
private string areaOrganizzativaOmogenea;
public string AreaOrganizzativaOmogenea
{
get { return areaOrganizzativaOmogenea; }
set { areaOrganizzativaOmogenea = value; }
}
private string siglaAOO;
public string SiglaAOO
{
get { return siglaAOO; }
set { siglaAOO = value; }
}
private string siglaUOR;
public string SiglaUOR
{
get { return siglaUOR; }
set { siglaUOR = value; }
}
private int idUor;
public int IdUor
{
get { return idUor; }
set { idUor = value; }
}
private bool attiva;
public bool Attiva
{
get
{
return attiva;
}
set
{
attiva = value;
}
}
private int alias;
public int Alias
{
get
{
return alias;
}
set
{
alias = value;
}
}
public override int GetHashCode()
{
// Get the hash code for the Textual field if it is not null.
int hashTextual = siglaAOO == null ? 0 : siglaAOO.GetHashCode();
// Get the hash code for the Digital field.
int hashDigital = idUor.GetHashCode();
// Calculate the hash code for the object.
return hashDigital ^ hashTextual;
}
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
UOR p = obj as UOR;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (idUor == p.idUor) && (siglaAOO.Equals(p.siglaAOO));
}
public bool Equals(UOR p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (idUor == p.idUor) && (siglaAOO.Equals(p.siglaAOO));
}
}
我知道我可以迭代 visibUtils.Uors 列表,并检查此列表中是否存在具有相同 SiglaAOO 和 SiglaUOR 的对象> 字段值是否是我必须插入的当前对象。
但是...存在一些更聪明的方法吗? (也许与 lambda 表达式有关)
最佳答案
正如你所拥有的 GetHashCode
和Equals
已定义,最好使用 HashSet<UOR>
而不是List<UOR>
。因为HashSet
将检查 O(1)
是否存在复杂性,而 List
- 与 O(n)
.
var interimSet = new HashSet<UOR>();
foreach (int idUor in visibilitaPostRidistribuzioni)
{
var uor = UorSQL.GetUorFromId(siglaAOO, idUor, dbConfig);
interimSet.Add(uor); //which is the same as: if(!interimSet.Contains(uor))interimSet.Add(uor);
}
visibUtils.Uors = interimSet.ToList();
关于c# - 如何使用 C# 检查一个对象(我必须插入到列表中)是否已经在列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57288913/