【问题标题】:Filter repeated (by integer) items in a List<Tuple<int,Image>> and create a Dictionary<int, List<Image>> C#过滤 List<Tuple<int,Image>> 中重复的(按整数)项目并创建 Dictionary<int, List<Image>> C#
【发布时间】:2017-02-06 02:11:46
【问题描述】:

我有一个元组列表,每个元组都有一个整数和一个图像,该列表有几个具有相同整数值但图像不同的项目,所以我想获取列表中具有相同整数的项目,然后创建一个列表中相应项目的图像列表。

例如,假设我有 3 张图片

imageL1_1imageL1_2 在列表中,具有相同的整数 1

imageL2_1 在列表中,值为 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 ));

我想过滤这些项目并创建一个如下所示的字典:

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}
};

我在尝试:

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 
    }
}

我很难弄清楚将项目保存在列表中还是将元素保存在字典中的条件,如何解决?

这可以使用LINQ 来完成吗?

【问题讨论】:

    标签: c# linq list dictionary


    【解决方案1】:

    试试这个。

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

    基本上,这会按给定键 (tuple.Item1) 对 source 中的项目列表进行分组,然后将分组转换为 Dictionary

    【讨论】:

    • 有趣的解决方案,所以分组包含所有具有相同键的图像,它是正确的吗?
    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多