Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast List<object> to List<myclass> c#

By this code I got list of selected rows in AspxGrid.

string[] fieldName = new string[] { "UserId", "Name", "Address" };
List<object> SelectedList = Grid.GetSelectedFieldValues(fieldName);

Now I want to perform one of the below operation.

  1. Filter this List of object by userid where userid = 1 using linq
  2. Cast this List<object> into List<Users>

I have tried following two methods but Exception occurs.

Unable to cast object of type 'System.Object[]' to type 'CubeDataObject.Claims'.

List<Users> mylist = (List<Users>)(Object)SelectedList;
List<Users> listd = SelectedList.Select(n => (Users)n).ToList();

I have also tried so many other methods too but tired.

like image 764
Gujjar Avatar asked Nov 10 '16 11:11

Gujjar


People also ask

Can Object be cast to list?

you can always cast any object to any type by up-casting it to Object first. in your case: (List<Customer>)(Object)list; you must be sure that at runtime the list contains nothing but Customer objects.

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList); Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .

How do you cast an Object to a specific class?

The cast() method of java. lang. Class class is used to cast the specified object to the object of this class. The method returns the object after casting in the form of an object.

Can you make a list of objects in Java?

You could create a list of Object like List<Object> list = new ArrayList<Object>() . As all classes implementation extends implicit or explicit from java. lang. Object class, this list can hold any object, including instances of Employee , Integer , String etc.


2 Answers

For this simple tast the Cast-extension-method on Enumerable exists:

var myList = SelectedList.Cast<User>();

Now you can easily filter:

var result = myList.Where(x => x.userId == 1);
like image 176
MakePeaceGreatAgain Avatar answered Sep 19 '22 12:09

MakePeaceGreatAgain


It seems that you have list of boxed object[]. So, you need to unbox it and get the values of UserId, Name, Address by its corresponding index.
Here is example:

List<Users> mylist = SelectedList
    .Where(item => (int)((object[])item)[0] == 1)
    .Select(item =>
    {
        var values = (object[])item;

        return new Users()
        {
            UserId = (int)values[0],
            Name = (string)values[1],
            Address = (string)values[2]
        };
    })
    .ToList();
like image 25
nempoBu4 Avatar answered Sep 18 '22 12:09

nempoBu4