Can anyone tell when to use Add() and AddRange() of ArrayList?
If you want to add a large number of values at one time, use AddRange.
If you are only adding a single value or adding values infrequently, use Add
Difference Between Add and AddRange
Add---------It is used to add the item into the list one by one.
AddRange-----------It is used to add the bulk of list item into the another list.
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);
output:
//The output of list1 contains
Malathi,
Sandhiya,
Ramya,
Mithra,
Dharshini
//The output of list2 Contains
Malathi,
Sandhiya,
Ramya,
Mithra,
Dharshini
C# List class represents a collection of a type in C#. List.Add(), List.AddRange(), List.Insert(), and List.InsertRange() methods are used to add and insert items to a List.
AddRange - AddRange adds an entire collection of elements. It can replace tedious foreach-loops that repeatedly call Add on List.
public virtual void AddRange (System.Collections.ICollection c);
Add - Add method adds an object to the end of the List.
public virtual int Add (object value);
Example: Now set an array of elements to be added to the list.
// array of 4 elements
int[] arr = new int[4];
arr[0] = 500;
arr[1] = 600;
arr[2] = 700;
arr[3] = 800;
Use the AddRange() method add the entire collection of elements in the list −
List<int> list = new List<int>();
list.AddRange(arr);
But if you want to use List.Add() method,
List<int> list = new List<int>();
list.Add(100);
list.Add(200);
list.Add(300);
list.Add(400);
For details, you can check Insert an Item into a C# List
If You want to add single variable in List, then Add() is used.
But if you want to add List or multiple variable in List, then AddRange() can be used
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;
It will add result of List s to List t along with result of List t.
Difference b/w Add() and AddRange() methods is very straight forward
Add() is used to add an element in the list.
AddRange() is used to add a range of elements(multiple elements) at once in the list.
Note: Multiple elements can be another entire Array, HashTable, SortedList, ArrayList, BitArray, Queue, and 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);
}
}
}
}
Related
public class LIST
{
public double num;
public double longi;
public double ux;
public double vy;
}
public static List<LIST> LIST1= new List<LIST>();
LIST L1 = new LIST();
L1.ux= // I take l1.ux from stream reader by reading a file and made this
for
L1.vy=.. the other parameters
L1.longi=..
L1.num=....
LIST1.Add(L1)
Here my problem is ı made a list that contains 4 parameters. But ı want to find just one parameter value for instance L1.num how can I take this value from a list?
var indexOfLISTObject = 1 //you need to know which object from LIST1 you want to use
var numParamOfLISTObject = LIST1[indexOfLISTObject].num;
Please Don't name your object LIST. It will create readability issues down the line for you. Name the object what a particular item in your list will represent.
To access a particular property from an item in list you can do following
List l1 = new list();
//Add items ...
//Print property from particular index
Console.WriteLine(l1[index].propertyname);
Put the paremeters inside a list one by one.
in your example you want the parameter num.
List parameterNum = new List();
parameterNum = l1.Select(x => x.Num).ToList();
parameterNum has now the list of Num from l1 list.
If you mean to find/search for a particular value, you could also use System.Linq. For example if you would like to find a member where num is set to 2, you could do this:
LIST1.Where(item=>item.num==2).FirstOrDefault()
According my Understanding If you want to Get objects that contain with specific parameter
then you can use this code
public static List<LIST> LIST1= new List<LIST>();
LIST L1 = new LIST();
var SearchedValue= List1.where(x=>x.num==L1.num).tolist();
if you want just L1.num value then you can use this line (if searched record will 1 then you should use this)
var SearchedValue= List1.where(x=>x.num==L1.num).FirstOrDefault().num;
you can use
LIST1[index].propertyname //index is index of list element and propertyname is the name of property you want to access
I want to alter the items of a list, which they are lists too.
I tried:
for (int i = pChain.Count -1; i> 0; i --)
{
List<String> item = pChain[i];
item = item.RemoveSequentialRepeats().ToList();
}
Where the RemoveSequentialRepeats is a static function like:
public static IEnumerable<T> RemoveSequentialRepeats<T>(
this IEnumerable<T> source) ....
As I trace the code, the function changes the list and removes the consecutive repeated items, but it is not stored in the main list pChain. Do I do something wrong?
From your example, it appears the RemoveSequentialReapeats doesn't edit the list but creates a new one instead. So, you're assigning a new value to item, and pChain doesn't update and remains with the original list. What you should do is add the line
pChain[i] = item;
To fix the problem you've to assign back result from Linq statement to pChain.
pChain[i] = item;
Code can be even simplified and make it one liner code.
pChain = pChain.Select(li=> li.Select(item=>item.RemoveSequentialRepeats()).ToList());
I have a ListBox with Integers in it that gets them from a SQL database. Now I wanted to put these elements into a List when they get selected but somehow it won't work. Here is the code:
List<Int32>typeElements = new List<Int32>();
if(form1.listBox.SelectedIndex != -1)
{
foreach (var selectedItem in form1.listBox.SelectedItems)
{
typeElements.Add(selectedItem);
}
}
He tells me he can't convert object to int and that the method has some invalid arguments. How to handle that?
ListBox.SelectedItems is a collection of objects. You can't simply take an element from this collection and add it to a typed list of integers.
You need a conversion
typeElements.Add(Convert.ToInt32(selectedItem));
If you want to use Linq and the IEnumerable extensions then you could write your loop in one line
// List<Int32>typeElements = new List<Int32>();
List<Int32> typeElements = form1.listBox.Items.Cast<int>().ToList();
EDIT:
Following your comment then you need to extract the Integer element from the DataRowView
DataRow row = (selectedItem as DataRowView).Row;
typeElements.Add(row.Field<int>("NameOfYourDataBaseIntegerField"));
Try this (using System.Linq):
OfType() is an extension method, so you need to use System.Linq
List<Int32> selectedFields = new List<Int32>();
selectedFields.AddRange(listbox.CheckedItems.OfType<Int32>());
Or just do it in one line:
List<Int32> selectedFields = listbox.CheckedItems.OfType<Int32>().ToList();
There is a array list that contain generic lists. How can i access the variables that in generic list? But i want to access the variables via the array list.
ArrayList TheList = new ArrayList();
List<NewType>[] GenericLists = new List<NewType>[4];
GenericLists[0].Add(variable);
.
.
.
for (int i = 0; i < 4; i++)
{
TheList.Add(GenericLists[i]);
}
How can i print the variables via the Array list?
You need to iterate over the items of your ArrayList and cast each item to List<NewType> then you can iterate over the items in the lists and display them or whatever you want...
foreach(var list in TheList)
{
var currentList = (List<NewType>)list;
...
}
Or you can use Linq methods to cast them:
foreach(var list in TheList.Cast<NewList>())
These assumes that all items in the array list are of type NewList. Otherwise you will get an InvalidCastException at runtime. To avoid this you can use is or as operators to check if the type is NewList, or you can use OfType method which does this for you:
foreach(var list in TheList.OfType<NewList>())
I have two List<int> instances. Now I want to combine them into a third list.
public List<int> oldItemarry1 // storing old item
{
get
{
return (List<int>)ViewState["oldItemarry1 "];
}
set
{
ViewState["oldItemarry1 "] = value;
}
}
public List<int> newItemarry1 // storing new item
{
get
{
return (List<int>)ViewState["newItemarry1 "];
}
set
{
ViewState["newItemarry1 "] = value;
}
}
public List<int> Itemarry1 // want to combine both the item
{
get
{
return (List<int>)ViewState["Itemarry1 "];
}
set
{
ViewState["Itemarry1 "] = value;
}
}
Please some one tell me how to do that?
LINQ has the Concat method:
return oldItemarry1.Concat(newItemarry1).ToList();
That just puts the list together. LINQ also has Intersect method, which will give you only items that exist in both lists and the Except method, which only gives you items that are present in either, but not both. The Union method give you all items between the two lists, but no duplicates like the Concat method.
If LINQ is not an option, you can just create a new list, add the items from each list to both via AddRange, and return that.
EDIT:
Since LINQ is not an option, you can do it a few ways:
Combine lists with all items, including duplicates:
var newList = new List<int>();
newList.AddRange(first);
newList.AddRange(second);
return newList
Combine without duplicate items
var existingItems = new HashSet<int>();
var newList = new List<int>();
existingItems.UnionWith(firstList);
existingItems.UnionWith(secondList);
newList.AddRange(existingItems);
return newList;
This of course assumes that you're using .NET 4.0, since that is when HashSet<T> was introduced. It's a shame you aren't using Linq, it really excels at things like this.
Use the Union method; it will exclude duplicates.
int[] combinedWithoutDups = oldItemarry1.Union(newItemarry1).ToArray();
You can combine two lists:
List<int> result = new List<int>();
result.AddRange(oldList1);
result.AddRange(oldList2);
The list result now has all the elements of both lists.
Here's one way to approach it:
public List<int> Itemarry1()
{
List<int> combinedItems = new List<int>();
combinedItems.AddRange(oldItemarray1);
combinedItems.AddRange(newItemarray1);
return combinedItems;
}
As a best practice, try to use IEnumerable rather than List when you can. Then, to make this work best you will want a read-only property:
public IEnumerable<int> Itemarry1 // want to combine both the item
{
get
{
return ((List<int>)ViewState["oldItemarry1 "]).Concat((List<int>)ViewState["Itemarry1"]);
}
}
If you need a point in time combination of two lists into a third list, Union and Concat are appropriate, as mentioned by others.
If you want a 'live' combination of the two lists (such that changes to the first and second list are automatically reflected in the 'combined' list) then you may want to look into Bindable LINQ or Obtics.