如何将文本文件中的行存储到列表中?

时间:2016-07-04 08:50:20

标签: c# visual-studio

我正在Visual Studio中编写一个C#程序,它将读取文本文件并将这些行添加到列表中。 文本文件包含人名和年龄的行。

  Name: Amy
  Age: 30
  Name: Bob
  Age: 25
  ....

将文本文件作为参数发送到List函数。

在List函数中,我想从文本文件中读取每一行并将其添加到列表中(info1)。

我写了一段代码。但是当我运行代码时会出现构建错误。

中有错误
    info1.Add(line.ToString());

代码如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    class Class1
{

    public void Main()
    {
        List<Info> info1 = Load(@"filename.txt");

        Console.ReadKey();
    }


}


public List<Info> Load(string file)
    {
        List<Info> info1 = new List<Info>();

        using (StreamReader rdr = new StreamReader(file))
        {
            string line;

            while ((line = rdr.ReadLine()) != null)
            {
                info1.Add(line.ToString());                  

            }
        }
        return info1;
    }



public class Info
{

    public string Name { get; set; }
    public string Age { get; set; }

    public Info(string name, string age)
    {
        Name = name;
        Age = age;

    }

}

}

我不确定我犯的错误。我的代码中有错误吗?

编辑:我不确定如何纠正代码以确保我可以添加到列表中。我该如何纠正这些代码?

7 个答案:

答案 0 :(得分:2)

browser.find_element(:xpath, "Relevant Xpath").style('background-color') method returns .ToString(),但您尝试将其添加到string列表中。这就是你的代码无法编译的原因。

您需要阅读两行(首先是姓名信息,第二行是年龄信息),create a new Info实例和store it in the list

答案 1 :(得分:0)

您正尝试添加List<Info> string个对象。 因为它是类型违规,编译器可能会给你一个转换错误

答案 2 :(得分:0)

列表的类型为Info,但代码正在尝试添加string,这会导致异常。

这应解决您的问题,解决方案使用Linq

public List<Info> Load(string file)
{
    List<Info> info1 = new List<Info>(); 
    var contents = File.ReadLines(file)
        .Select(x=> new {item=x, index=i})
        .GroupBy(x=> x.index/2)
        .Select(x=> new Info() 
         {
             Name = x.First().item.Split(':')[1],    // Name
             Age = x.Last().item.Split(':')[1]      // Age
         }
        .ToList();

    info1.AddRange(content);

    return info1;
}

答案 3 :(得分:0)

info1.Add(line.ToString());

Infoinfo1,但您在列表中添加了private static final int ITEM_NUM = 5 ; // 5 for smooth pager title strip private void addFragment(String title, String className) { if (fragments.size() < ITEM_NUM) { Bundle b = new Bundle(); b.putInt("pos", fragments.size()); fragments.add(Fragment.instantiate(this, className, b)); } titles.add(title); itemList.add(className); }

public static class MyFragmentPageAdapter extends FragmentPagerAdapter { private HashMap<Long, Fragment> mItems = new HashMap<Long, Fragment>(); public MyFragmentPageAdapter(FragmentManager fragmentManager) { super(fragmentManager); } @Override public long getItemId(int position) { int id = java.lang.System.identityHashCode(fragments.get(position)); return id; } @Override public Fragment getItem(int position) { long id = getItemId(position); if (mItems.get(id) != null) { return mItems.get(id); } Fragment f = fragments.get(position); return f; } @Override public int getCount() { return ITEM_NUM; } @Override public CharSequence getPageTitle(int position) { String t = titles.get(getItem(position).getArguments() .getInt("pos")); return t; } @Override public int getItemPosition(Object object) { for (int i = 0; i < ITEM_NUM; i++) { Fragment item = (Fragment) fragments.get(i); if (item.equals((Fragment) object)) { return i; } } return POSITION_NONE; } }

您应该创建一个新的 itemList = new ArrayList<String>(); fragments = new ArrayList<Fragment>(); titles = new ArrayList<String>(); addFragment("Title1", Fragment1.class.getName()); ... addFragment("TitleN", FragmentN.class.getName()); mAdapter = new MyFragmentPageAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id...); mViewPager.setAdapter(mAdapter); mViewPager.setCurrentItem(2); currPage = 2; visibleFragmentPos = 2; mViewPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int curr) { dir = curr - currPage; currPage = curr; } private void shiftRight() { fragments.remove(0); int pos = visibleFragmentPos + 3; if (pos > itemList.size() - 1) pos -= itemList.size(); if (++visibleFragmentPos > itemList.size() - 1) visibleFragmentPos = 0; insertItem(4, pos); } private void shiftLeft() { fragments.remove(4); int pos = visibleFragmentPos - 3; if (pos < 0) pos += itemList.size(); if (--visibleFragmentPos < 0) visibleFragmentPos = itemList.size() - 1; insertItem(0, pos); } private void insertItem(int datasetPos, int listPos) { Bundle b = new Bundle(); b.putInt("pos", listPos); fragments.add(datasetPos, Fragment.instantiate(ctx, itemList.get(listPos), b)); } @Override public void onPageScrollStateChanged(int state) { if (state == ViewPager.SCROLL_STATE_IDLE) { if (dir == 1) { shiftRight(); } else if (dir == -1) { shiftLeft(); } mAdapter.notifyDataSetChanged(); currPage = 2; } } }); 对象并将其添加到private void replaceActivity(LoginModel loginModel) { Context context = activity.getApplicationContext(); Intent intent = new Intent(context, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("accessKey", loginModel.getAccessKey()); intent.putExtra("loginData", loginModel.getUserData()); context.startActivity(intent); activity.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); }

答案 4 :(得分:0)

string[] lines = File.ReadAllLines(@"filename.txt");
List<Info> infos = new List<Info>();
foreach(var line in lines)
{   
    string name = "";
    string age = "";
    if(line.StartsWith("Name:"))
    {
        name = line.Replace("Name: ", "");      
    }
    else if(line.StartsWith("Age:"))
    {
        age = line.Replace("Age: ", "");
    }
    Info info = new Info(name, age);
    infos.Add(info);
}

答案 5 :(得分:0)

这是如何从每一行创建一个Info对象:

public static List<Info> Load(string file)
{
    List<Info> results = new List<Info>();

    string name = null;
    foreach (var line in File.ReadAllLines(file))
    {
        bool isName = false;
        string age = null;
        if (line.Contains("Name:"))
        {
            name = null;
            isName = true;
        }

        string value = line.Split(':')[1];

        if (isName)
            name = value;
        else
            age = value;

        if (!isName)
        {
            results.Add(new Info(name, age));
            name = null;
        }

    }

    return results;
}

答案 6 :(得分:0)

您需要创建Info类的新实例以添加Info列表,因为您的列表类型是“Info”并且您正在尝试添加“string”

    using (StreamReader rdr = new StreamReader(file))
    {
        string line;// for Name
        string line2;//for Age

        while ((line = rdr.ReadLine()) != null)
        {
            line2= rdr.ReadLine();
            info1.Add(new Info(line,line2));                  

        }
    }
    return info1;
}