转换文本文件到列表<&诠释GT; [英] Convert text file to List<int>

查看:223
本文介绍了转换文本文件到列表<&诠释GT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我需要为 IEnumberable< ID号的CSV文件; INT> 。我试图从A到尽可能简单地B,并与下面的想法来到了:

I have a CSV file of ID numbers that I need as an IEnumberable<int>. I was trying to get from A to B as simply as possible, and came up with the following idea:

Global.migrated = File.ReadAllText(Global.migrationList).Split(',').Cast<int>().ToList<int>();

当我运行这一点,虽然,我被告知,中投是无效的。我也试着阅读到一个字符串列表和铸造为int:

When I run this, though, I'm told that the Cast is invalid. I also tried reading to a String list and casting to int:

List<string> myTemp = File.ReadAllText(Global.migrationList).Split(',').ToList<string>();
Global.migrated = myTemp.Cast<int>();



但是,这引发了以下错误:

But this raises the following error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'System.Collections.List<int>.' An explicit conversion exists. Are you missing a cast?



我不明白。我想投的对象不是的IEnumerable< INT> 在这种情况下。这应该是一个列表与LT;串> 。我怕我失去了一些关于铸造的工作方式很重要。

I don't understand. The object I'm trying to cast isn't an IEnumerable<int> in this case. It should be a List<string>. I'm afraid I'm missing something important about how casting works.

推荐答案

您需要将对象转换,不投了。

You need to convert the object, not cast it.

File.ReadAllText(Global.migrationList).Split(',')
   .Select(x=> Convert.ToInt32(x)).ToList();

一个转换是尽可能多的字符串值是一个字符串,而不是从一个转换不同只要在CLR数而言。如果对象是投是一个浮动小数双击或任何类型的数字再投将正常工作。但是,当对象是字符串的CLR没有办法投的对象。你可以,但是,将一个字符串整数这实际上解析对象,并返回一个新的对象,而不是转换的CLR类型。

A cast is different from a convert in as much as the string value is a string, and not a number as far as the CLR is concerned. If the object being cast was a float, decimal, double or any numerical type then cast would work fine. But as the object is a string the CLR has no way to cast the object. You can, however, convert a string to an integer which actually parses the object and returns a new object rather than just converting its CLR type.

虽然你可能认为铸造和加工作为是在实际应用非常相似,他们是非常不同的事情的CLR

While you may think of casting and converting as being very similar in practical uses, they are very different things to the CLR

这篇关于转换文本文件到列表&LT;&诠释GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆