Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ "Where" condition -> change value of property

Tags:

c#

linq

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?

like image 827
Rahul Patil Avatar asked Mar 16 '16 17:03

Rahul Patil


1 Answers

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

like image 168
D Stanley Avatar answered Nov 10 '22 17:11

D Stanley