开发者

Read and modify objects in a generic List<T>

I am working with a generic List which I add Employee objects to.

I know how to add and remove from it, but how do I "read" object data from it and how do I access methods and properties for a specific开发者_StackOverflow object in the list.

Let's say the Employee class contains the property below, how do I access it to modify the objects data?

public string FirstNameData
{
   get { return v_firstName; }
   set { v_firstName = value; }
}


Assuming:

var myList = new List<Employee>();

You have many options here...

First, you can index it directly:

var firstName = myList[0].FirstNameData

You can enumerate over it:

foreach(var employee in myList)
  ProcessName(employee.FirstNameData);

If you are using .Net 3.5 or greater, you can use Linq exetnsions:

var firstName = myList.First().FirstNameData;
var allFirstNames = myList.Select(employee => employee.FirstNameData);

It all depends on what you want to do...


You can iterate through the list and edit them, e.g.

public void KnightEmployees(List<Employee> employeeList)
{
    foreach(Employee employee in employeeList)
    {
        if (employee.Gender == Gender.Male)
        {
            employee.FirstNameData = "Sir " + employee.FirstNameData;
        }
        else
        {
            employee.FirstNameData = "Dame " + employee.FirstNameData;
        }
    }
}

or access them by index in the list which gives you an object you can use as normal, e.g.

employeeList[0].FirstNameData = "Bob";

Is that the sort of thing you meant?


Are you looking for indexes?

List<Employee> list = new List<Employee>();
list[0] = new Employee();
list[0].FirstNameData = "John";


Hard to tell exactly what you're asking, but if you know which employee in the list you want, your code would probably look something like this:

var emps = new List<Employee>();
emps.Add(...);
...
Console.WriteLine(emps[3].FirstName); //the 4th employee in the list

And this is somewhat unrelated to your question, but you may want to try making your properties a bit more brief by using automatic properties (which don't require a private backing variable) in C# like so:

public string FirstNameData {
   get; set;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜