Jobje325
Jobje325

Reputation: 55

Count elements with a condition in a sublist with linq

I am trying to get some values from a list of objects that have a list themselves but I am struggling with the Linq query to achieve this. I want to show a user the amount of Events they haven't responded to.

I have a list of Events of which each Event has a list of EventUsers, these EventUsers have a boolean HasResponded and a UserId. I want to retrieve the amount of events for which a certain user has not responded yet.

For simplicity I have left out the attributes of the objects that I dont need in the Linq query.

Event class:

    public class Event
    {
        public List<EventUser> EventUsers { get; set; }
    }

EventUser class:

    public class EventUser
    {
        public int EventId { get; set; }
        public Event Event { get; set; }
        public long UserId { get; set; }
        public User User { get; set; }

        public bool HasResponded { get; set; }
    }

My linq query should look something like this, but I cant get it to work:

_eventManager.QueryEvents().Where(x => x.StartTime > DateTime.Today && x.EventUsers.Select(z => z.UserId == userId && z.HasResponded)).Count()

How would I go about creating this Linq query? Any help is much appreciated!

Upvotes: 2

Views: 1788

Answers (2)

Dogu Arslan
Dogu Arslan

Reputation: 3384

_eventManager.QueryEvents().Where(x => x.StartTime > DateTime.Today)
                           .SelectMany(x => x.EventUsers)
                           .Count(z => z.UserId == userId && !z.HasResponded)

Upvotes: 5

jdweng
jdweng

Reputation: 34429

Need to use a SelectMany :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            EventManager _eventManger = new EventManager();

            var results = _eventManger.events.SelectMany(x => x.EventUsers.Select(y => y))
                .GroupBy(x => x.UserId)
                .Select(x => new { UserId = x.First().UserId, count = x.Where(y => y.HasResponded == false).Count() })
                .ToList();

        }
    }
    public class EventManager
    {
        public List<Event> events { get; set; }
    }
    public class EventUser
    {
        public int EventId { get; set; }
        public Event Event { get; set; }
        public long UserId { get; set; }
        public User User { get; set; }

        public bool HasResponded { get; set; }
    }
    public class Event
    {
        public List<EventUser> EventUsers { get; set; }
    }
    public class User
    {
        public List<EventUser> EventUsers { get; set; }
    }
}

Upvotes: 1

Related Questions