Search code examples
c#asp.net-mvclistentity-frameworkicollection

How should i use collection?


I have a list of strings which is populated by a query from database (entity frameworks):

 var accountIds = new List<string>();

Now I want to add two list of strings to my collection, for example, I have these two queries:

 using (var myketDB = new MyketReadOnlyDb())
            {
                if (!string.IsNullOrWhiteSpace(name))
                {
                    accountIds = myketDB.AppDevelopers
                        .Where(n => n.RealName.Contains(name))
                        .Select(e => e.Email).ToList();                  
                }                
                if (!string.IsNullOrWhiteSpace(email))
                {
                    accountIds = myketDB.Accounts
                      .Where(e => e.Mail.Contains(email))
                      .Select(e => e.Email).ToList();
                }                 
            }

So with this query accountIds changes which I don't want this to happen. I want to have both lists in accountIds. something like this :

accountIds.add(//first query);
accountIds.add(//2nd query);

something like a union (I don't want to use union). I'm new to the collection list. many thanks.


Solution

  • If you want to add multiple items to existing list then .AddRange method will do this for you

    accountIds.AddRange(myketDB.AppDevelopers
                            .Where(n => n.RealName.Contains(name))
                            .Select(e => e.Email).ToList());
    
    accountIds.AddRange(myketDB.Accounts
                          .Where(e => e.Mail.Contains(email))
                          .Select(e => e.Email).ToList());
    

    Or more simply, first collect query result to variable and then add these result to existing list like,

    var appDevEmails = myketDB.AppDevelopers
                                .Where(n => n.RealName.Contains(name))
                                .Select(e => e.Email).ToList();
    
    var accountsEmails = myketDB.Accounts
                              .Where(e => e.Mail.Contains(email))
                              .Select(e => e.Email).ToList();
    
    accountIds.AddRange(appDevEmails);
    
    accountIds.AddRange(accountsEmails);
    

    Further Reading:

    List.AddRange(IEnumerable) Method