Reputation:
I have a list of objects, where I only want to add a new object to it, if the list does not already contain an object with matching properties, here is how I am trying to do it:
reservation = new ForecastReservationAssignees();
string extractWeekNumber = Regex.Match(weekNumberValue.Value.ToString(), @"\d+").Value;
int weekNumber = Int32.Parse(extractWeekNumber);
if ((reservationAssigneeList.Any(i => i.AvailableFor != weekNumber))
&& (reservationAssigneeList.Any(i => i.EmployeeName != employeeNameValue.Value.ToString())))
{
reservation.AvailableFor = weekNumber;
// Add it.
reservation.EmployeeName = employeeNameValue.Value.ToString();
// Add object.
reservationAssigneeList.Add(reservation);
}
First I create a new object, which has properties EmployeeName
, a string and AvailableFor
which is an int. I extract the number from a string i got elsewhere and parse the number to an int. Then comes the if statement. Here I want to check if the list already contains these properties. Essentially what I want is, to only add an employee a single time, and then that employee can have multiple AvailableFor
which is weeks, although only the same week one time. So en xample would be:
> Employee1
Week 11
Week 12
Week 13
So no employee name twice, and no week twice for each employee. The weeks can be the same for multiple employees though, so first and second employee both have the same week.
When I run the above code, I get nothing, nothing gets added at all. What could I be doing wrong?
Upvotes: 2
Views: 73
Reputation: 8926
Doing two .Any()
calls like you are will check the two independently, i.e. they don't have to be part of the same reservation. Try this for your if statement
if (reservationAssigneeList.Any(i => (i.AvailableFor != weekNumber) && (i.EmployeeName != employeeNameValue.Value.ToString()) ) )
{
That should make it so the same reservation has to match not match on AvailableFor and EmployeeName
Upvotes: 2
Reputation: 52952
Your if
statement is incorrect:
if ((reservationAssigneeList.Any(i => i.AvailableFor != weekNumber))
&& (reservationAssigneeList.Any(i => i.EmployeeName != employeeNameValue.Value.ToString())))
You're saying if ANY item has AvailableFor not matching weekNumber, AND any item has an employee name that isn't equal to the employee name value.
You need to combine them.
if ((reservationAssigneeList.Any(i => i.AvailableFor != weekNumber && i.EmployeeName != employeeNameValue.Value.ToString())))
That way you'll only check each individual item to see if they match.
Upvotes: 2