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

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

问题描述

我再次发布我的问题,因为我无法在其中添加我的答案,所以这是代码

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] ={"firstname","lastname"}[1]={"firstname2","secondname2"}

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

这些值附加在 Person 类中,因此如果我想更改索引 [1] 的姓氏值,该怎么做?我可以获得索引 [1] 值,但如何访问链接到该索引的 Person 变量

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).

尝试使用 List(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天全站免登陆