0

I'm using C# and asp.net.

I am trying to separate an email address during a SQL Select query located inside the rest of my C# code. My goal is to display a series of email addresses and each email address's domain names on a webpage. These emails are stored in a SQL database, and I am using a SQL Select query to access them. If someone's email is "john@gmail.com", then I want to display on a webpage "john@gmail.com" and "gmail.com." However, I keep getting an 'Index was outside the bounds of the array,' when it comes to my Split method.

I don't understand why this is happening, because if I replace x.EmailDomain with a generic string like "hello@gmail", then the program correctly returns "gmail.com" for EmailDomain. Also, if I take away the four string lines and simple put string emailDomainEnd = x.EmailDomain;, then the program will return a normal email address, so I know that the variable of string emailDomainStart accepts the information from x.EmailDomain correctly. I don't understand then why it is not being Split correctly in string[]parts = emailDomainStart.Split(new[] {'@'});

        if (sortProperty != null)
        {
            groupMemberGrid.DataSource = groupMembers.Select(gm => new MemberData()
            {
                FirstName = gm.Person.FirstName,
                LastName = gm.Person.LastName,
                Email = gm.Person.Email,
                EmailDomain = gm.Person.Email
            }).Distinct().Sort(sortProperty).ToList()
            .Select(x =>
            {
                string emailDomainStart = x.EmailDomain;
                string[] parts = emailDomainStart.Split(new[] {'@'});
                string username = parts[0];
                string emailDomainEnd = parts[1];
                return new
                {
                    x.FirstName,
                    x.LastName,
                    x.Email,
                    EmailDomain = emailDomainEnd,
                };
            })
            .ToList();   
        }

I've spent several hours on this and I am not sure how to fix it. I've only been coding for a year, so any help you could provide would be welcomed, as I have never encountered this error before.

RMB3030
  • 1
  • 1
  • Set a breakpoint before the split and check your data. Does `emailDomainStart` contain a `@` symbol? Probably not, thus `parts` will only have one element and thus `parts[1]` is invalid – derpirscher May 08 '23 at 06:09
  • Does this answer your question? [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – derpirscher May 08 '23 at 06:16

0 Answers0