Search code examples
linqmodelwebapi

C# LINQ - Loop through list to get Data


Would you please show me how to put a comma delimited string with email addresses ([email protected], [email protected], [email protected],...) into LINQ list then loop through each email address and go to SQL database to get name, address, phone number and return these back. EmailList below contains [email protected], [email protected], [email protected],..

public class PersonalInfo
{
   public string firstname {get; set;}
   public string lastname {get; set;}
   public string address {get; set;}
   public string phonenumber {get; set;}
}

public PersonalInfo GetInfo(string EmailList)
{
    ....
}

I can do the part to get info from SQL table. Just need help to loop through EmailList, call method to get data then return the data back to PersonalInfo.


Solution

  • When you have a string that you want to break apart on a particular character, you can use the Split() method. The caveat is that if you don't have a clear delimiting character you might split something you don't intend to. The comma is not commonly found in email addresses so this should be fine. The Split() method will return an array of strings.

    The next caveat is that "[email protected], [email protected]" will leave a space character before the "def" of the second email address. To remove these you can use the Trim() method of a string. Trim() will remove whitespace from the start and end of a string. Trim() is non-destructive so you need to store the results.

    The below method uses split to get an array with each entry being an email address. Then the Select() linq method is used to iterate each email address and return the Trim() result. Now the emails variable is an IEnumerable<string> with each string being an email that can be used to do the database lookup. I changed the return type on the Function to be a List<PersonalInfo> as I assume you are wanting to look up each person and return all results.

    public List<PersonalInfo> GetInfo(string EmailList)
    {
        List<PersonalInfo> output = new();
        var emails = EmailLIst.Split(',').Select(x => x.Trim());
    
        foreach (var email in emails)
        {
            // table lookup
            PersonalInfo info = GetFromTable(email);
            output.Add(info);
        }
        return output;
    }