6

I am struggling to fix the following problem:

I have list of object and object type is int:

int a = 1;
  int b = 2;
  int c = 3;
  List<object> kk = new List<object>( );
  kk.Add( ( object )a );
  kk.Add( ( object )b );
  kk.Add( ( object )c );

and I want to cast the List<object> to List<objecttype> and in above example object type is int. I want to cast List<object> to List<int>. Is there a way address this problem?

I am looking for generic solution and assume no knowledge of casting type.

enter image description here


Combine iOS and Web analytics

I am using Google analytics for my Web application and iOS application. iOS application is practically an equivalent of its Web counterpart (they have same views, same functionalities). I would like to have a combined report analyzing usage of both iOS and Web app together. That means sum of all pageviews, tracking user's actions...

4

5 回答 5

18

使用 linq 的两种方法

如果任何对象不是int.

var ints = kk.Cast<int>().ToList();

这个版本将只留下那些可以转换为int.

var ints = kk.OfType<int>().ToList();
于 2013-05-24T09:54:01.947 回答
5

也许你可以尝试这样的事情:

List<object> objects = new List<object>();
List<int> ints = objects.Select(s => (int)s).ToList();

应该适用于所有类型。

所以总的来说:

List<object> objects = new List<object>();
List<objecttype> castedList = objects.Select(s => (objecttype)s).ToList();
于 2013-05-24T09:58:50.920 回答
1

尝试这个:

var newList = kk.Cast<int>().ToList();
于 2013-05-24T09:57:11.600 回答
1
   var typeofkk = kk.ToArray( ).Select( x => x.GetType( ) ).ToArray( ).FirstOrDefault( );
   Array ll = Array.CreateInstance( typeofkk, kk.Count );
   Array.Copy( kk.ToArray (), ll, kk.Count );

也许,这不是我正在寻找的解决方案,但它以某种方式解决了我的问题。

于 2013-05-27T14:32:53.567 回答
0

尝试.Cast<int>()在您的列表中使用kk.

于 2013-05-24T09:54:39.730 回答