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 'WhereSelectEnumerableIterator
2[System.Collections.Generic.KeyValuePair
2[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?