有谁能告诉我何时使用 Add()
和 AddRange()
两个方法呢?它们都属于 ArrayList
类。
有谁能告诉我何时使用 Add()
和 AddRange()
两个方法呢?它们都属于 ArrayList
类。
Add
:它用于逐个将项目添加到列表中。
AddRange
:它用于将大量列表项添加到另一个列表中。List<string>list1=new List<string>();//using Add
List<string>list2=new List<string>();//using AddRange
list1.Add("Malathi");
list1.Add("Sandhiya");
list1.Add("Ramya");
list1.Add("Mithra");
list1.Add("Dharshini");
list2.AddRange(list1);
list1
的输出包含:
list2
的输出包含:
public virtual void AddRange (System.Collections.ICollection c);
public virtual int Add (object value);
示例:现在设置一个元素数组以添加到列表中。
// array of 4 elements
int[] arr = new int[4];
arr[0] = 500;
arr[1] = 600;
arr[2] = 700;
arr[3] = 800;
List<int> list = new List<int>();
list.AddRange(arr);
但是如果您想使用List.Add()方法,
List<int> list = new List<int>();
list.Add(100);
list.Add(200);
list.Add(300);
list.Add(400);
有关详细信息,您可以查看将项目插入到C#列表中。
var t = (from t1 intable1
join t2 in table2 on t1.t1id equals t2.t2id
select new ABCViewModel
{
FirstName = t1.firstname,
LastName = t1.Lastname
})
.where(t2.age>35)
.ToList();
var s = (from t1 intable1
join t2 in table2 on t1.t1id equals t2.t2id
select new ABCViewModel
{
FirstName = t1.firstname,
LastName = t1.Lastname
})
.where(t2.age < 35)
.ToList();
t.AddRange(s);
return t;
Add()
和AddRange()
方法的区别非常明显。
Add()
用于向列表中添加一个元素。
AddRange()
用于一次性添加一系列元素(多个元素)到列表中。
注意:多个元素可以是另一个完整的Array
、HashTable
、SortedList
、ArrayList
、BitArray
、Queue
或者Stack
。
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//create the first arraylist
ArrayList arraylist1 = new ArrayList();
arraylist1.Add(5);
arraylist1.Add(7);
//create the second arraylist
ArrayList arraylist2 = new ArrayList();
arraylist2.Add("Five");//add the single value at time to the arraylist
arraylist2.Add("Seven");//add the single value at time to the arraylist
//perform AddRange method
arraylist1.AddRange(arraylist2);//adding the arraylist as bulk in another arraylist
// Display the values.
foreach (object i in arraylist1)//iterating the arraylist1 value to object
{
Console.WriteLine(i);
}
}
}
}
Add
添加一个单一的值,例如Add(1)
;而AddRange
则添加一个IEnumerable<T>
类型的多个值,例如AddRange(new int[] {1, 2, 3})
。 - Dmitry BychenkoArrayList
,就不要用了。那是在C#没有泛型的旧时代。你应该改用List<T>
。 - Soner Gönül