2011-03-14 83 views
1

我有一个屏幕附在这里,我需要知道我怎么可以将列表转换为长列表?将此var转换为长整型列表?

var x = SchedulerMatrixStorage.Resources.Items.Select(col => col.Id); 

其中,编号为类型的Object

enter image description here

回答

5

由于您的清单似乎是同质的,你可以利用这一点是.NET框架的一部分内置转换功能:

var x = SchedulerMatrixStorage.Resources.Items 
     .Select(col => Convert.ToInt64(col.Id)).ToList(); 

Convert静态类提供了几个转换函数,其中一组将把各种类型的对象转换为各种内置值类型,如long。大多数这些功能也有一个超载,需要一个object参数(我假设你的收藏基本包含)。

注意,这个函数会在运行时,如果所提供的对象是什么,不能转换成long(比如,如果你要传递,比如说,一个Form),但你的截图来看这会失败为你工作。

2

您可以在Select语句中使用long.Parse(),因为从你的截图它看起来像值Items集合中可能是字符串:

var x = SchedulerMatrixStorage.Resources.Items.Select(col => 
    long.Parse(col.Id.ToString())).ToList(); 

x将被解析为键入System.Collections.Generic.List<long>

+1

为什么'Parse'?我认为这是对象,而不是一个字符串。 – 2011-03-14 17:22:42

+0

无论如何,如果所有对象的类型都是'long','Parse'优于'Cast'的优点是什么? – 2011-03-14 17:22:56

+1

@gaearon他的第一项是:'“-1”',这是一个字符串。 – CodingGorilla 2011-03-14 17:23:41

0

认为这应该做你想做的

var x = SchedulerMatrixStorage.Resources.Items.Select(col => col.Id).Cast<long>().ToList(); 
+1

与同样的答案一样,这会对他失败。他的第一个项目是一个字符串。 – 2011-03-14 17:43:13

0

也许是最快捷的方法是这样的:

var x = SchedulerMatrixStorage.Resources.Items.Select(col => col.Id).Cast<long>(); 

虽然你应该确保你只得到了ID所不久便前装箱作为一个对象。

+0

这会因提供的值而失败,因为第一个字符串是字符串。 – 2011-03-14 17:42:53

2

如果Idobject类型,但值始终是一个字符串,你可以使用:

var x = SchedulerMatrixStorage.Resources 
           .Items 
           .Select(col => long.Parse((string)col.Id) 
           .ToList(); 

但是,目前还不清楚的是,结果总是一个字符串。您需要提供更多关于col.Id的信息。

一般情况下,你想是这样的:

var x = SchedulerMatrixStorage.Resources 
           .Items 
           .Select(ConvertColumnId) 
           .ToList(); 

private static long ConvertColumnId(object id) 
{ 
    // Do whatever it takes to convert `id` to a long here... for example: 
    if (id is long) 
    { 
     return (long) id; 
    } 
    if (id is int) 
    { 
     return (int) id; 
    } 
    string stringId = id as string; 
    if (stringId != null) 
    { 
     return long.Parse(stringId); 
    } 
    throw new ArgumentException("Don't know how to convert " + id + 
           " to a long"); 
} 
0

嗯,我设法将第一个字符串"-1"转换为合适的长度。行var x = SchedulerMatrixStorage.Resources.Items.Select(col => Convert.ToInt64(col.Id)).ToList();现在适合我。身份证将永远是一个长期的。有了这个规则,有没有最好的方法来完成这个?我的意思是,我的任务已经完成,但希望现在如果LINQ提供一个更好的方法...

enter image description here

+1

发布答案时,您无法提出新问题。当你发布答案时,没有人会收到通知,所以没有人会看到这一点。问一个新问题,或者添加一个评论给别人的答案,提到他的名字,像这样:@Hassan。 – 2011-03-17 04:16:35

+0

谢谢@ilyakogan – DoomerDGR8 2011-03-17 15:53:10