How to avoid nested foreach using Linq?

Hi,

I have the following code. How can I avoid foreach using linq?

foreach(var number in phoneNumbers)
{
	foreach(var i in number.key)
	{
		if(students[i].phone == null)
		{
			students[i] = new People { phone = number.Value };
		}
		else
		{
			students[i].phone = number.Value;
		}
	}
}

Open in new window


please note
Dictionary<string[], string> phoneNumbers
List<People> students
IsabellAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Bill PrewIT / Software Engineering ConsultantCommented:
What's in the dictionary?  It looks like the values are phone numbers (in string), but is the key actually an array, that seems a little odd.  If so, what are the numbers in that array, and why to multiples tie to a single phone number.

Maybe some sample data would help, I'm just having trouble understanding the data model.


»bp
Bill PrewIT / Software Engineering ConsultantCommented:
Are you sure it's not

Dictionary<string, string[]> phoneNumbers

That would make more sense to me.  One string value being the key for the dictionary, and the stored value being an array of phone numbers.

What are the actual keys that you are using, it looked like an integer was being used that was the index of the student list, but not really sure if that was the case, and how changing it to a string now affected that?

Again, some sample data for the dictionary and the student list would be helpful.


»bp
IsabellAuthor Commented:
Please forgive me Bill,
my original question is correct. it should be <int[], string>

var phoneNumbers = new Dictionary<int[], string>()
{
	{new int[]{1, 3}, "222-222-2222"},
	{new int[]{2}, "333-333-3333"},
	{new int[]{4, 5, 6}, "444-444-4444}
}

Open in new window


so the scenario is multiple students share the same phone number.
so students[1] and students[3] will have "222-222-2222",
students[2] will have "333-333-3333",
and students[4], students[5], and students[6] will have "444-444-4444"
Does this make sense now?

I deleted my previous comment since it adds extra confusion.
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

Bill PrewIT / Software Engineering ConsultantCommented:
Another expert may have some tricks I am not aware of, but I'm not sure you can get to anything better than that with LINQ.  To me, the issue is that you can't access the dictionary directly for a given student, since their "id" could be any element of the array that is the dictionary key.  So there is no way to "join" or access the corresponding dictionary entry for each student.

If you had just an int key to the dictionary, one per student, with their phone number, then it would be doable.  But I assume you don't want to do that for duplication or something?


»bp
it_saigeDeveloperCommented:
Perhaps something like this:
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q29146030
{
    class Program
    {
        static void Main(string[] args)
        {
            var students = new List<Person>(Enumerable.Range(0, 7).Select(i => default(Person))).ToArray();
            var numbers = new Dictionary<int[], string>
            {
                { new[] {1, 3}, "222-222-2222" },
                { new[] {2}, "333-333-3333" },
                { new[] {4, 5, 6}, "444-444-4444" }
            };

            foreach (var person in (from pair in numbers from i in pair.Key select new { Index = i, Phone = pair.Value }))
            {
                if (Equals(students[person.Index]?.Phone, null))
                {
                    students[person.Index] = new Person { Phone = person.Phone };
                }
                else
                {
                    students[person.Index].Phone = person.Phone;
                }
            }

            foreach (var output in students.Select((s, i) => $"Student {i}'s phone number is {(s?.Phone ?? "not defined")}"))
            {
                Console.WriteLine(output);
            }
            Console.ReadLine();
        }
    }

    class Person
    {
        public string Phone { get; set; }
    }
}

Open in new window

Which produces the following output -Capture.PNGPersonally though, I would rethink this design and use lists instead.  Perhaps add an id field to the person class and the id is the id of the person as well as the integer in the dictionary.  I would also use a dictionary of string, List<int> instead of the other way around; e.g. -
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q29146030
{
    class Program
    {
        static void Main(string[] args)
        {
            var students = new List<Person>();
            var numbers = new Dictionary<string, List<int>>
            {
                { "222-222-2222", new List<int> { 1, 3 } },
                { "333-333-3333", new List<int> { 2 } },
                { "444-444-4444", new List<int> { 4, 5, 6 } }
            };

            foreach (var person in (from pair in numbers from id in pair.Value select new { Id = id, Phone = pair.Key }))
            {
                var student = students.FirstOrDefault(s => Equals(s.Id, person.Id));
                if (Equals(student, null))
                {
                    students.Add(new Person { Id = person.Id, Phone = person.Phone });
                }
                else
                {
                    student.Phone = person.Phone;
                }
            }

            foreach (var output in students.Select(s => $"Student {s.Id}'s phone number is {(s?.Phone ?? "not defined")}"))
            {
                Console.WriteLine(output);
            }
            Console.ReadLine();
        }
    }

    class Person
    {
        public int Id { get; set; }
        public string Phone { get; set; }
    }
}

Open in new window

Which now produces the following output -Capture.PNG-saige-

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
kaufmed   ( ⚆ _ ⚆ )Patches? We Ain't Got No Patches! We Don't Need No Patches! I Don't Have to Push You No Stinkin' Patches!Commented:
I have to agree with Bill Prew on this one:  I think your version is much more readable than what it_saige offers. LINQ doesn't seem like a good fit here.

My biggest problem with your code is that it's not abundantly clear what the Key property represents (in a business sense). I see that you're using it to index the students variable, but that doesn't really tell me how students is connected to Key. Always err on the side of clarity versus succinctness. Your code will suffer if it's not easy to decipher what the code actually does.
IsabellAuthor Commented:
Thank you all!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.