How to avoid nested foreach using Linq?

Isabell
Isabell used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Bill PrewTest your restores, not your backups...
Top Expert 2016

Commented:
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 PrewTest your restores, not your backups...
Top Expert 2016

Commented:
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

Author

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.
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Bill PrewTest your restores, not your backups...
Top Expert 2016

Commented:
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
Commented:
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-
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

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.

Author

Commented:
Thank you all!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial