简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM