How to read a text file and add the data to a int array in C#?

后端 未结 4 1370
深忆病人
深忆病人 2021-01-27 06:13

I\'m trying to read a text file which contains numbers separated by a comma. When I read using File.Readline() I get it to a string[]. I need to conver

4条回答
  •  一生所求
    2021-01-27 06:43

    I think this is what you are after:

        static void Main(string[] args)
        {
            var sr = new StreamReader(@"d:\test.txt");
            long[] data = ExtractData(sr).ToArray();
        }
    
        private static IEnumerable ExtractData(StreamReader sr)
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                var items = line.Split(',');
                foreach (var item in items)
                {
                    yield return Convert.ToInt64(item);
                }
            }
        }
    

    With my test file (d:\test.txt) holding:

    1,2,3,4,5
    1,2,3,4
    

    I get the array containing:

    1,2,3,4,5,1,2,3,4
    

    EDIT

    As Monroe pointed out, I missed the fact you wanted an array of arrays. Here's another version that gives such a jagged array. Still keeping yield in though ;)

        static void Main(string[] args)
        {
            var sr = new StreamReader(@"d:\test.txt");
            var data = ExtractData(sr).ToArray();
        }
    
        private static IEnumerable ExtractData(StreamReader sr)
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                yield return line.Split(',').Select(i => Convert.ToInt64(i)).ToArray();
            }
        }
    

提交回复
热议问题