Add two array list values to arraylist c# - c#

I'm completely new to c# sorry if asked here anything meaningless for you guys but I would like to know how can I solve this type of situation.
I having two arraylist's as shown below:
ArrayList OldLinks = new ArrayList();
ArrayList NewLinks = new ArrayList();
ArrayList mylist = new ArrayList();
foreach (string oldlink in OldLinkArray)
{
OldLinks.Add(oldlink);
}
foreach (string newlink in NewLinkArray)
{
NewLinks.Add(newlink);
}
Now I need to get them as single arraylist with two items each
I need to get it as
ArrayList NewList = new ArrayList();
NewList.Add(oldlink, newLink);

ArrayList NewList = new ArrayList();
NewList.AddRange(OldLinks);
NewList.AddRange(NewLinks);
You can use AddRange() method or AddAll() method to accomlish this.
NewList.AddAll(OldLinks);
NewList.AddAll(NewLinks);
Or
To create multidimensional arrayList you can use dictionary
public class MultiDimList: Dictionary<string, string> { }
MultiDimList NewList = new MultiDimList ();
for(int i; i<OldLinks.Count ; i++)
{
NewList.Add(OldLinks[i].ToString(), NewLinks[i].ToString());
}
provided both ArrayLists have the same count

Xou could do something like this.. The string Version is problaby not the best solution but can work. Sorry Code is note tested
public class Link
{
public string Version {get;set;}
public string Value {get;set;}
}
Use it Like
List<Link> linkList = new List<Link>();
linkList.AddRange(OldValues)
linkList.AddRange(OldValues)
var oldList = linkList.Where(l => l.Version.Equals("old")).ToList();
var newList = linkList.Where(l => l.Version.Equals("new")).ToList()

As you need both oldlink and newlink together as an item in resulted arraylist, you could use Zip Linq extension and do this.
ArrayList NewList = new ArrayList();
NewList.AddRange(OldLinks.Cast<string>()
.Zip(NewLink.Cast<string>(), (x,y) => string.Format("{0},{1}",x,y))
.ToArray()
);
Result ArrayList contains both (oldlink, newlink).

Related

Create List with name from variable

Is it possible in C# to create a list and name it from a variable or similar?
Let's say I have a list with 10 rows in it:
a, b, c, d, e, f, g, h, i, j
Can I make 10 lists from this list, each having a name like one of the rows?
Something like
List<string> myList = new List<string>();
foreach (var line in myList)
{
List<string> line = new List<string>();
}
What I want is to make a few lists to store data in, but I won't know the names before the program runs so it needs to generate those dynamically.
Sounds like you want a Dictionary of List<string>s:
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
foreach (var line in myList)
{
dict.Add(line, new List<string>());
}
Now you can access each list based on the original string we used for the key:
List<string> aList = dict["a"];
You could try something like this:
var newList = new Dictionary<string, List<string>>();
foreach (var line in myList)
{
newList.Add(line, new List<string>());
}
This will give you the data structures in which to store your new data and will allow you to reference them based on the names in the first list.
It seems that you want a Dictionary<String, List<String>> like this:
var data = myList
.ToDictionary(line => line, line => new List<string>());
And so you can
check if "variable" exists
if (data.ContainsKey("z")) {...}
address "variable"
data["a"].Add("some value");
add "variable"
data.Add("z", new List<string>());

Convert List<int>to List<List<int>>

Can i convert List<int>to List<List<int>> in c#?
When I use such construction
List<int>element=new List<int>();
List<List<int>>superElement= new List<List<int>>(element);
I get a fault,but can I do this in another way?
You can do it like this:
List<List<int>> superElement = new List<List<int>>();
superElement.Add(element);
List<int>element=new List<int>();
List<List<int>>superElement= new List<List<int>> { element };
That'll work. You can't pass the list in the constructor.
Try this :
var element = new List<int>();
var superElement = new List< List<int> >(){ element };
Yes. You can use the collection initializer
List<int> element = new List<int>();
List<List<int>> superElement = new List<List<int>> { element };
http://msdn.microsoft.com/en-gb/library/vstudio/bb384062.aspx
If you just want to initialize the List, then
List<List<int>>superElement= new List<List<int>>();
works; if you want it to contain one (empty) element initially then
List<List<int>>superElement= new List<List<int>>{element};
will do it.
Due to the fact I do not believe the other answers have really put in much effort to help, I am going to post what I believe to be a more complete and useful answer.
To start with, and for completeness I will show how to achieve what was actually trying to be done. To create a List of Lists you can do this:
List<int> element = new List<int>();
List<List<int>> superElement = new List<List<int>>();
superElement.Add(element);
But as it stands, it doesn't make a lot of sense why you would want to do this, and after some comment probing (hope it didn't hurt) we have discovered that you want to pair up an ID with a List of integers. I would suggest taking a different approach to this.
Personally, I would create a class to hold my data, and then create a single List for those items, like so:
public class MyData
{
public int ID {get; set;}
public List<int> MyValues {get;set;}
public MyData()
{
MyValues = new List<int>();
}
}
Then you can do this:
List<int> element = new List<int>();
MyData data = new MyData();
data.ID = 1;
data.MyValues = element;
List<MyData> superElement = new List<MyData>();
superElement.Add(data);
Which would allow querying like so:
MyData data1 = superElement.SingleOrDeafult(x => x.ID == 1);
List<int> element = data1.MyValues;
Assuming you have Linq available.
An alternate method could be to use a dictionary, like so:
Dictionary<int, List<int>> superElement = new Dictionary<int, List<int>>();
superElement.Add(1, element);
where 1 is an ID, which you can call like so:
List<int> element = superElement[1];

How to convert ArrayList into string array(string[]) in c#

How can I convert ArrayList into string[] in C#?
string[] myArray = (string[])myarrayList.ToArray(typeof(string));
use .ToArray(Type)
string[] stringArray = (string[])arrayList.ToArray(typeof(string));
A simple Google or search on MSDN would have done it. Here:
ArrayList myAL = new ArrayList();
// Add stuff to the ArrayList.
String[] myArr = (String[]) myAL.ToArray( typeof( string ) );
Try do that with ToArray() method.
ArrayList a= new ArrayList(); //your ArrayList object
var array=(String[])a.ToArray(typeof(string)); // your array!!!
using System.Linq;
public static string[] Convert(this ArrayList items)
{
return items == null
? null
: items.Cast<object>()
.Select(x => x == null ? null : x.ToString())
.ToArray();
}
You can use CopyTo method of ArrayList object.
Let's say that we have an arraylist, which has String Type as Elements.
strArrayList.CopyTo(strArray)
Another way is as follows.
System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add("1");
al.Add("2");
al.Add("3");
string[] asArr = new string[al.Count];
al.CopyTo(asArr);

How do I copy items from list to list without foreach?

How do I transfer the items contained in one List to another in C# without using foreach?
You could try this:
List<Int32> copy = new List<Int32>(original);
or if you're using C# 3 and .NET 3.5, with Linq, you can do this:
List<Int32> copy = original.ToList();
I see that this answer is still getting upvotes. Well, here's a secret for ya: the above answer is still using a foreach. Please don't upvote this any further.
To add the contents of one list to another list which already exists, you can use:
targetList.AddRange(sourceList);
If you're just wanting to create a new copy of the list, see the top answer.
For a list of elements
List<string> lstTest = new List<string>();
lstTest.Add("test1");
lstTest.Add("test2");
lstTest.Add("test3");
lstTest.Add("test4");
lstTest.Add("test5");
lstTest.Add("test6");
If you want to copy all the elements
List<string> lstNew = new List<string>();
lstNew.AddRange(lstTest);
If you want to copy the first 3 elements
List<string> lstNew = lstTest.GetRange(0, 3);
And this is if copying a single property to another list is needed:
targetList.AddRange(sourceList.Select(i => i.NeededProperty));
This method will create a copy of your list but your type should be serializable.
Use:
List<Student> lstStudent = db.Students.Where(s => s.DOB < DateTime.Now).ToList().CopyList();
Method:
public static List<T> CopyList<T>(this List<T> lst)
{
List<T> lstCopy = new List<T>();
foreach (var item in lst)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, item);
stream.Position = 0;
lstCopy.Add((T)formatter.Deserialize(stream));
}
}
return lstCopy;
}
Easy to map different set of list by linq without for loop
var List1= new List<Entities1>();
var List2= new List<Entities2>();
var List2 = List1.Select(p => new Entities2
{
EntityCode = p.EntityCode,
EntityId = p.EntityId,
EntityName = p.EntityName
}).ToList();
Adding to the top answers, if you want copies of "the objects in the list", then you can use Select and make the copies. (While the other answers make "a copy of a list", this answer makes "a list of copies").
Suppose your item has a Copy method:
List<MyObject> newList = oldList.Select(item => item.Copy()).ToList();
Or that you can create a new object from the previous one with a constructor:
List<MyObject> newList = oldList.Select(item => new MyObject(item)).ToList();
The result of Select is an IEnumerable<MyObject> that you can also pass to AddRange for instance, if your goal is to add to an existing list.
OK this is working well
From the suggestions above GetRange( ) does not work for me with a list as an argument...so sweetening things up a bit from posts above: ( thanks everyone :)
/* Where __strBuf is a string list used as a dumping ground for data */
public List < string > pullStrLst( )
{
List < string > lst;
lst = __strBuf.GetRange( 0, __strBuf.Count );
__strBuf.Clear( );
return( lst );
}
public static List<string> GetClone(this List<string> source)
{
return source.Select(item => (string)item.Clone()).ToList();
}
Here another method but it is little worse compare to other.
List<int> i=original.Take(original.count).ToList();

Populate list from array

if i have an array. can i populate a generic list from that array:
Foo[] fooList . . . (assume populated array)
// This doesn't seem to work
List<Foo> newList = new List<Foo>(fooList);
You could convert the array to a List:
string[] strings = { "hello", "world" };
IList<string> stringList = strings.ToList();
You are looking for List(t).AddRange Method
As #korki said, AddRange will work, but the code you've posted should work fine. For example, this compiles:
var i = new int[10];
var list = new List<int>(i);
Could you show us more of your code?

Categories