MorkaLork Development

Interesting stuff I've picked up over the years...

AddRange()

2009-04-17 07:22:07 | 244 views | csharp class method tutorial add range addrange collection

When you add items to a list you can do it either by the Add() method or by the AddRange() method. The AddRange() method let's you add a collection all at once.

This code will show how it works:

Fplayer.cs




namespace TestApp
{
public class Fplayers
{
public string Name;
public int Age;
public string Team;

public Fplayers(string name, int age, string team)
{
this.Name = name;
this.Age = age;
this.Team = team;
}
}
}


Program.cs




using System;
using System.Collections.Generic;

namespace TestApp
{
class Program
{
public static void Main(string[] args)
{
//Create the list
List<Fplayers> BestPlayers = new List<Fplayers>();

//Create three Fplayer objects
Fplayers player1 = new Fplayers("Zlatan Ibrahimovic", 27, "Inter");
Fplayers player2 = new Fplayers("Olof Mellberg", 31, "Juventus");
Fplayers player3 = new Fplayers("Marcus Rosenberg", 26, "Werder Bremen");

//Create an array and add the three Fplayer objects
Fplayers[] FplRange = new Fplayers[]{player1, player2, player3};

//Add the array to the list with the AddRange() method
BestPlayers.AddRange(FplRange);

//Output the result
Console.WriteLine("Great fooball players:\n\n");
BestPlayers.ForEach(delegate(Fplayers fpl)
{
Console.WriteLine("Name: {0}\nAge: {1}\nTeam: {2}\n", fpl.Name, fpl.Age, fpl.Team);
});
Console.Read();
}
}
}


The output will look like this:

imagehttp://admin.morkalork.com/uploads/images/csharp/listAddRange.png


Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.