2

Is there any shortcut or better way to typecast List<bool> to List<object>?

I know i can do that by looping and casting individual item but i want to know is this possible to cast entire list in one statement.


Eclipse: Change the block comment style of ctrl+shift+/

The keyboard shortcut ctrl+shift+/ produces comments in the format of:

/*comment*/

How can I change the shortcut so that it adds a space before and after the asterisk?

/* comment */

Many thanks!

4

3 回答 3

9

您可以使用以下Enumerable.Cast<T>方法执行此操作:

List<bool> bools= GetBoolList();
IList<Object> objects= bools.Cast<Object>().ToList();
于 2012-05-10T13:14:00.273 回答
6

执行此操作的非 LINQ 方法是List.ConvertAll

List<bool> b = new List<bool> { true, false, true };
List<object> o = b.ConvertAll(x => (object)x);

由于此方法知道创建新列表的大小,因此对于大型列表,它可能比 LINQ 版本更快。

于 2012-05-10T13:20:07.567 回答
3
List<bool> list = new List<bool>{true,true,false,false,true};
List<Object> listObj1 = list.Select(i=> (Object)i).ToList();// First way
List<Object> listObj2 = list.Cast<Object>().ToList();// Second way 
List<Object> listObj3 = list.OfType<Object>().ToList();// Third way 

以下是在linqpad中快速测试

 list.Dump();
 listObj1.Dump();
 listObj2.Dump();
 listObj3.Dump();
于 2012-05-10T13:18:08.797 回答