Cannot implicitly convert type 'System.Collections.Generic.List<System.Collections.Generic.IEnumerable<xxx>>' to 'System.Collections.Generic.List<xxx>

StackOverflow https://stackoverflow.com/questions/23646898

  •  22-07-2023
  •  | 
  •  

سؤال

I am getting the following error. I googled it for more than a day but I cant find the exact solution, Please help me Thank you

ERROR: Cannot implicitly convert type System.Collections.Generic.List<System.Collections.Generic.IEnumerable<ADCO.eJMC.EntityDataModel.ShareholderUser>> to System.Collections.Generic.List<ADCO.eJMC.EntityDataModel.ShareholderUser>

I used the following code

List<ShareholderUser> list = new List<ShareholderUser>();
list = dataContext.EJMCShareholderApprovals
                  .Include(s => s.Shareholder.ShareholderUsers)
                  .Where(e => e.EJMCRequestId == requestId)
                  .Select(s => s.Shareholder.ShareholderUsers
                                .Where(x => x.AccessMode == true))
                  .ToList();
هل كانت مفيدة؟

المحلول

The problem is that at the moment, you're selecting a sequence of sequences - one sequence of ShareholderUser items for each Shareholder. If you just want a list of ShareholderUser items, you need to flatten the results. That's most easily done using SelectMany, which can actually replace your Select call in this case.

List<ShareholderUser> list = dataContext.EJMCShareholderApprovals
                                 .Where(e => e.EJMCRequestId == requestId)
                                 .SelectMany(s => s.Shareholder.ShareholderUsers)
                                 .Where(x => x.AccessMode == true)
                                 .ToList();

Note how breaking the query over multiple lines makes it much simpler to read, too. Also, there's no point in initializing the list variable to a new List<ShareholderUser> if you're then immediately going to give it a different value. I've also removed the Include call, as that was unnecessary - you're explicitly selecting Shareholder.ShareholderUsers in the query, so you don't need to include it.

نصائح أخرى

This should do it?

var list = dataContext.EJMCShareholderApprovals
              .Include(s => s.Shareholder.ShareholderUsers)
              .Where(e => e.EJMCRequestId == requestId)
              .Select(s => s.Shareholder.ShareholderUsers
              .Where(x => x.AccessMode == true)).ToList();

though you are doing select on to ShareHolderUsers? Are you trying to get a list of ShareHolderUsers or a list of lists of ShareHolderUsers?

.Select(s => s.Shareholder.ShareholderUsers
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top