Click here to Skip to main content
15,879,184 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

I have code like below.

C#
var ds = from DataRowView rowView in view
                                               select new CM.Models.ClassName
                                               {
                                                   Note = rowView["Type"].ToString(),

                                               };

method.Welcome((ClassName)ds).Process();


When i cast like this it will give me below error.

Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Data.DataRowView,ClassName ClassName

Can any one help me on this?

Regards,
Viprat
Posted
Comments
[no name] 10-Nov-14 8:56am    
Try with adding .ToList().
I think here ds would give a list of objects.
viprat 10-Nov-14 8:58am    
no that is given only one object.
[no name] 10-Nov-14 9:00am    
Can you just tell me briefly what exactly you want from this LINQ?
What is the scenario?
Sergey Alexandrovich Kryukov 10-Nov-14 9:00am    
First of all: if a compiler tells you "unable to cast", who told you that your next task is to cast it?
—SA
viprat 10-Nov-14 9:08am    
its compile successfull but once i run i will get above error.

1 solution

The Linq query returns an IEnumerable of your class - and you can;t cast that to a single value any more than you can use an array of integers tin a simple arithmetic operation:
C#
int[] ar = GetInts();
int x = ar + 6;

Instead, either return a single item using FirstOrDefult, or check the count and fetch the first member of the collection to pass to your method. Neither way will need casting as the Linq query specifically returns a collection of a named type.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900