1

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.

MLavoie
  • 9,671
  • 41
  • 36
  • 56
Ali Eshghi
  • 1,131
  • 1
  • 13
  • 30

1 Answers1

4

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

er-sho
  • 9,581
  • 2
  • 13
  • 26