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

Gujjar picture Gujjar · Nov 10, 2016 · Viewed 9.1k times · Source

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.

Answer

HimBromBeere picture HimBromBeere · Nov 10, 2016

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