LINQ Where clause & # 8594; change property value

I have a list of meetings in which I have another list of participants.

The model is like 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 a meeting list

List<Meeting> meetings = GetMeetings();

Now I want to mask the Title meetings where one of the users is bot@domain.com . I can achieve this in several LINQ queries, but I'm looking for an optimized LINQ query.

Can anyone help me with this?

What I tried -

 var maskedMeetings = meetings.Where(x = x.Users.Any(a => a.Email.Equals(" bot@domain.com "))); meetings = appointments.Except(maskedMeetings).ToList(); maskedMeetings = maskedMeetings.Select(x => { x.Title = "Bot"; return x; }).ToList(); meetings = meetings.Concat(maskedMeetings).ToList(); 

Can someone help me with an optimized way of writing this query?

Rahul.

+7
c # linq
source share
1 answer

If I read your code correctly, you request a subset of my items, removing those items from the original list, modifying the items in the subset, and putting the changed items in the list. There is no need to go through all this; just change the items in the list.

Linq, however, is for queries, not updates. To update the objects in the collection just use a loop:

 foreach(var meeting in meetings) { if(meeting.Users.Any(a => a.Email.Equals(" bot@domain.com "))) 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(" bot@domain.com "))) { meeting.Title = "Bot"; } 

Please note that performance probably will not vary significantly between the two

+9
source share

All Articles