I have a list of meetings, inside which I have another list of attendees.
The model is similar to this:
public class Meeting
{
public string Id { get; set; }
public string Title { get; set; }
public List<User> Users { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
I have list of Meetings
: List<Meeting> meetings = GetMeetings();
Now I want to mask the Title
of the meetings where one of the users is [email protected]
. I can achieve this in multiple LINQ queries but I am looking for one optimized LINQ query.
Here's what I tried:
var maskedMeetings = meetings.Where(x = x.Users.Any(a => a.Email.Equals("[email protected]")));
meetings = appointments.Except(maskedMeetings).ToList();
maskedMeetings = maskedMeetings.Select(x => { x.Title = "Bot"; return x; }).ToList();
meetings = meetings.Concat(maskedMeetings).ToList();
Can anyone help me find an optimized way of writing this query?
If I read your code right, you are querying for a subset of your items, removing those items from the original list, modifying the items in the subset, and putting the modified items back in the list. There's no need to go through all of that; just modify the items within the list.
Linq, however, is for querying, not updating. To update objects in a collection just use a loop:
foreach(var meeting in meetings)
{
if(meeting.Users.Any(a => a.Email.Equals("[email protected]")))
meeting.Title = "Bot";
}
or use Linq to pre-filter the list
foreach(var meeting in meetings.Where(x = x.Users.Any(a => a.Email.Equals("[email protected]")))
{
meeting.Title = "Bot";
}
Note that the performance will likely not be significantly different between the two
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With