C#如何读取链接到班级列表中的指数变量 [英] C# how to read index variables linked to the class in a list

查看:131
本文介绍了C#如何读取链接到班级列表中的指数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我再次发布我的问题,因为我不能把它添加我的答案,所以这里是code

I am posting my question again because i can not add my answers in it so here is the code

static void Main(string[] args)
{
    string fileA= "B.txt";
    IList listA= new ArrayList();

    FileReader(fileA, ref listA);

    for (int i = 0; i < listA.Count; i++)
    {
        Console.WriteLine(listA[i].ToString());
    }

    Console.ReadKey();
}

public static void FileReader(string filename, ref IList result)
{
    using (StreamReader sr = new StreamReader(filename))
    {
        string firstName;
        string SecondName;

        while (!sr.EndOfStream)
        {
            firstName= sr.EndOfStream ? string.Empty : sr.ReadLine();
            SecondName= sr.EndOfStream ? string.Empty : sr.ReadLine();

            result.Add(new Person(firstName, SecondName));
        }
    }
}

和我得到我的列表中为[0] =值{名字,姓氏}
[1] = {firsname2,secondname2}

and i am getting values in my list as [0] ={"firstname","lastname"} [1]={"firsname2","secondname2"}

这些值连接与Person类,所以,如果我想改变指数的姓氏值[1]那该怎么办呢?我可以得到该指数[1]的值,但是如何访问它们链接到该索引中的人变量

these values are attached with the Person class so if i want to change the lastname value of index [1] then how to do it? i can get the index [1] values but how to access the Person variable which are linked to that index

推荐答案

您正在使用的ArrayList 这是不是一个合适的数据结构,因为它会扔掉类型信息(除非你坚持使用.NET 1.1)。

You're using an ArrayList which isn't an appropriate data structure since it will throw away the type information (unless you're stuck with .NET 1.1).

尝试使用列表(T)

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

static void Main(string[] args)
{
    var file = "B.txt";
    var list = new List<Person>();

    ReadFile(file, list);

    list[1].LastName = "newValue";
}

private static void ReadFile(string file, List<Person> personList)
{
    var items = File.ReadLines(file)
                    // Take each value and tag it with its index
                    .Select((s, i) => new { Value = s, Index = i })
                    // Put the values into groups of 2
                    .GroupBy(item => item.Index / 2, item => item.Value)
                    // Take those groups and make a person
                    .Select(g => new Person { FirstName =  g.FirstOrDefault(), LastName = g.Skip(1).FirstOrDefault() });

    personList.AddRange(items);
}

这篇关于C#如何读取链接到班级列表中的指数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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