Here is a solution where you can use System.Linq to check for existing records in a list or in EntityFramework.
The trick is to read the obect from the list and check if the result was null, as in this code snippet:
var entityFirst = myUniqueInstance.SingleOrDefault(p => p.FirstName == newPersonFirst.FirstName && p.FamilyName == newPersonFirst.FamilyName);
if (entityFirst != null)
{
Console.WriteLine($"Rejected First: {newPersonFirst}");
throw new Exception($"Person {newPersonFirst} already exists in our List!");
}
else
{
myUniqueInstance.Add(newPersonFirst);
Console.WriteLine($"Added First: {newPersonFirst}");
}
using System;
using System.Collections.Generic;
using System.Linq;
namespace FindIfRecordExist
{
public class MyUniqueClass
{
public int MyUniqueClassID { get; set; }
public string FirstName { get; set; }
public string FamilyName { get; set; }
public MyUniqueClass()
{
}
public MyUniqueClass(string FirstName, string FamilyName)
{
this.FirstName = FirstName;
this.FamilyName = FamilyName;
}
public override string ToString()
{
return $"{FirstName} {FamilyName}";
}
}
class Program
{
static void Main(string[] args)
{
try
{
List<MyUniqueClass> myUniqueInstance = new List<MyUniqueClass>();
myUniqueInstance.Add(new MyUniqueClass("Donald", "Truman"));
myUniqueInstance.Add(new MyUniqueClass("Ronald", "Clinton"));
myUniqueInstance.Add(new MyUniqueClass("Bill", "Reagan"));
myUniqueInstance.Add(new MyUniqueClass("Hillary", "Bold"));
foreach(var p in myUniqueInstance)
{
Console.WriteLine($"Added: {p}");
}
try
{
MyUniqueClass newPersonFirst = new MyUniqueClass("Raymond", "Kennedy");
var entityFirst = myUniqueInstance.SingleOrDefault(p => p.FirstName == newPersonFirst.FirstName && p.FamilyName == newPersonFirst.FamilyName);
if (entityFirst != null)
{
Console.WriteLine($"Rejected First: {newPersonFirst}");
throw new Exception($"Person {newPersonFirst} already exists in our List!");
}
else
{
myUniqueInstance.Add(newPersonFirst);
Console.WriteLine($"Added First: {newPersonFirst}");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
MyUniqueClass newPersonSecond = new MyUniqueClass("Raymond", "Kennedy");
var entitySecond = myUniqueInstance.SingleOrDefault(p => p.FirstName == newPersonSecond.FirstName && p.FamilyName == newPersonSecond.FamilyName);
if (entitySecond != null)
{
Console.WriteLine($"Rejected Second: {newPersonSecond}");
throw new Exception($"Person {newPersonSecond} already exists in our List!");
}
else
{
myUniqueInstance.Add(newPersonSecond);
Console.WriteLine($"Added Second: {newPersonSecond}");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}