[英]Cast List<object> to List<myclass> c#
By this code I got list of selected rows in AspxGrid. 通过此代码,我获得了AspxGrid中所选行的列表。
string[] fieldName = new string[] { "UserId", "Name", "Address" };
List<object> SelectedList = Grid.GetSelectedFieldValues(fieldName);
Now I want to perform one of the below operation. 现在我想执行以下操作之一。
List<object>
into List<Users>
List<object>
强制转换为List<Users>
I have tried following two methods but Exception occurs. 我尝试了两种方法,但发生了异常。
Unable to cast object of type 'System.Object[]' to type 'CubeDataObject.Claims'.
无法将类型为“System.Object []”的对象强制转换为“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. 我也尝试了很多其他的方法,但累了。
For this simple tast the Cast
-extension-method on Enumerable
exists: 对于这个简单的尝试,存在
Enumerable
上的Cast
-extension方法 :
var myList = SelectedList.Cast<User>();
Now you can easily filter: 现在您可以轻松过滤:
var result = myList.Where(x => x.userId == 1);
It seems that you have list of boxed object[]
. 看来你有盒装
object[]
列表object[]
。 So, you need to unbox it and get the values of UserId
, Name
, Address
by its corresponding index. 因此,您需要将其解包并通过相应的索引获取
UserId
, Name
, Address
的值。
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();
Linq has a special method for casting lists: Linq有一个特殊的方法来构建列表:
List<Users> mylist = SelectedList.Cast<Users>().Where(u => u.userid == 1).ToList();
This should work, assuming the objects are actually castable to a Users object. 这应该有效,假设对象实际上可以转换为Users对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.