0

I'm really having trouble using Linq on a SortedList. I have a Class Library and a Test WinForms app. The class library code is:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JTS
{
    public static class Pictures
    {
        public static class PictureManagement
        {
            public static SortedList<int, Picture> PictureList = new SortedList<int, Picture>();

            public static class Acquire
            {
                public static Picture ById(int id)
                {
                    Picture picture = null;

                    if(PictureList != null)
                    {
                        picture = (Picture)from pic in PictureList
                                          where
                                              pic.Key == id
                                          select (pic.Value as Picture);
                    }
                    return picture;
                }
            }
        }

        public class Picture : PictureBox
        {
            public int Id { get; set; }

            public class PictureProperties
            {
                public string Name { get; set; }
                public string Extension { get; set; }
                public string OriginalPath { get; set; }
                public Image OriginalPhoto { get; set; }
                public string Credits { get; set; }

                public Size DesignTimeSize { get; set; }
                public Point DesignTimeLocation { get; set; }

            }

            public PictureProperties Properties { get; set; }

            public class PictureThumbnail
            {
                public string Name { get { return "T" + Name; } }
                public Size Size { get; set; }
            }

            public PictureThumbnail Thumbnail { get; set; }
        }
    }
}

and the Test winforms app code is:

using JTS;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void test()
        {
            for(int i = 0; i < 10; i++)
            {
                JTS.Pictures.PictureManagement.PictureList.Add(i, new JTS.Pictures.Picture()
                    {
                        Id = i,
                        Properties = new JTS.Pictures.Picture.PictureProperties()
                        {
                            Name = "Travis",
                            Credits = "people in here"
                        },

                        Thumbnail = new JTS.Pictures.Picture.PictureThumbnail()
                        {
                            Size = new Size(250, 250)
                        }
                    });

                Console.WriteLine("pics added to list");

                Console.WriteLine("getting Picture by id 3");

                JTS.Pictures.Picture pic = JTS.Pictures.PictureManagement.Acquire.ById(3);

                Console.WriteLine(pic.Id);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            test();
        }
    }
}

If you're going to paste this into VS, don't forget to Add System.Windows.Forms as a Reference to the class library.

The problem I'm having is when I run the Test winforms application, on FormLoad, I get an exception, which says:

An unhandled exception of type 'System.InvalidCastException' occurred in JTS.dll

Additional information: Unable to cast object of type 'WhereSelectEnumerableIterator2[System.Collections.Generic.KeyValuePair2[System.Int32,JTS.Pictures+Picture],JTS.Pictures+Picture]' to type 'Picture'.

Now, I know what an invalid cast is. But I don't know what it's referring to. Where have I made an invalid cast?

spike.y
  • 389
  • 5
  • 17

4 Answers4

4

According to the error message, the error is here:

picture = (Picture)from pic in PictureList
                               where  pic.Key == id
                               select (pic.Value as Picture);

Try this:

picture = from pic in PictureList
                      where  pic.Key == id
                      select (pic.Value as Picture)).FirstOrDefault();

Or, since it is a SortedList, why not simply use this?

var picture = PictureList[id];
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2
picture = (Picture)from pic in PictureList
                                          where
                                              pic.Key == id
                                          select (pic.Value as Picture);

This query returns IEnumerable<Picture>, not Picture.

Try this:

picture = (Picture)from pic in PictureList
                                          where
                                              pic.Key == id
                                          select (pic.Value as Picture).First();
Gusdor
  • 14,001
  • 2
  • 52
  • 64
1

This query returns an IEnumerable<T> after get executed:

from pic in PictureList
where pic.Key == id
select (pic.Value as Picture)

You can't cast it to single Picture, if you want to get a single item, use First or Single method.

(from pic in PictureList
where pic.Key == id
select (pic.Value as Picture)).First();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

Using Lambda:

Picture picture = PictureList.Where(pic => pic.Key == id).FirstOrDefault().Value;

This code replace the part where you doing a select from the PictureList collection. The problem with your code is that the where clause returns a collection of Picture and you're assigning the collection to a Picture which is not a collection, hence you're getting an InvalidCastException.

Gusdor
  • 14,001
  • 2
  • 52
  • 64
Bayeni
  • 1,046
  • 9
  • 16
  • What is the intent of this snippet? Should it be added or replaced? Where should it go? Why does it fix the problem? – Gusdor May 06 '14 at 09:28
  • This code replace the part where you doing a select from the PictureList collection. The problem with your code is that the "Where" clause return a collection of Pictures and you're assigning the collection to a Picture which is not a collection hence you're getting an InvalidCastException. – Bayeni May 06 '14 at 09:43