cMinor cMinor - 4 years ago 127
C# Question

Filter repeated (by integer) items in a List<Tuple<int,Image>> and create a Dictionary<int, List<Image>> C#

I have a list of tuples, each tuple has an integer and an image, the list has several items with the same integer value, but distinct image, so I want to get items in list with the same integer and then create a list of images from their corresponding item on list.

For instance suppose I have 3 images

imageL1_1 and imageL1_2 are on list with same integer 1

imageL2_1 is on list with value 2

Image imageL1_1 = new Image();
imageL1_1.Source = new BitmapImage(new Uri("Resources/image1.png", UriKind.Relative));
Image imageL1_2 = new Image();
imageL1_2.Source = new BitmapImage(new Uri("Resources/image2.png", UriKind.Relative));
Image imageL2_1 = new Image();
imageL2_1.Source = new BitmapImage(new Uri("Resources/image3.png", UriKind.Relative));
List<Tuple<int,Image>> source = new List<Tuple<int,Image>>();
source.Add(new Tuple<int,Image>(1,imageL1_1 ));
source.Add(new Tuple<int,Image>(1,imageL1_2));
source.Add(new Tuple<int,Image>(2,imageL2_1 ));


I want to filter these items and create a dictionary that looks like:

List<Image> l1 = new List<Image>();
l1.Add(imageL1_1);
l1.Add(imageL1_2);

List<Image> l2 = new List<Image>();
l2.Add(imageL2_1);

Dictionary<int, List<Image>> dictImages = new Dictionary<int, List<Image>>()
{
{1, l1},
{2, l2}
};


I was trying:

Dictionary<int, List<Image>> result = new Dictionary<int, List<Image>>();
List<Image> listIm = new List<Image>();
foreach (Tuple<int, Image> diff in temp)
{

//How should I save items until key is different??
if(someCondition)
{
listIm.Add(diff.Item2); //save item on temp list
}
else
{
result.Add(diff.Item1, listIm); //save result on Dictionary
listIm.Clear(); //clean list
}
}


I am having hard time to figure out the condition to either save item on list or save element on dictionary, How to solve it?

Could this be done using
LINQ
?

Answer Source

Try this.

Dictionary<int, List<Image>> result = 
    source.GroupBy(tuple => tuple.Item1, tuple => tuple.Item2)
        .ToDictionary(grouping => grouping.Key, grouping => new List<Image>(grouping));

Basically, this groups your list of items in source by the given key (tuple.Item1) and then converts the grouping into a Dictionary.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download