Convert List<int>to List<List<int>> - c#

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];

Related

How can I populate this complex List?

I have a complex List data structure which i want to populate but i just cant seem to find a way to seed values to it.
List<Dictionary<List<int>, int>> l1 = new List<Dictionary<List<int>, int>>();
I want something like this,
l1.add( (1,2,3), 6);
I want to add a list of numbers and its sum.
Really not sure why you're doing that but if you really have to
var list = new List<Dictionary<List<int>, int>>();
list.Add(new Dictionary<List<int>, int> {{ new List<int> { 1, 2, 3 }, 6}});
I doubt you really need a list of dictionary of list. Still, you can write some kind of extension method:
public static ListHelpers
{
public void AddSum(this List<Dictionary<List<int>, int>> list, params int[] values)
{
list.Add(new Dictionary<List<int>, int> { values.ToList(), values.Sum() });
}
}
Then use it with:
l1.AddSum(1, 2, 3);

Add two array list values to arraylist 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).

Is there something called array of list?

I declared something like this
List<double> close = new List<double>();
I pass this list to a function XYZ and the function will fill it up with value. As I need to run this XYZ function many times, is there a way to create a array of list so that I can access the third list element 7 by typing listarray[2][6].
I think you need something like this:
List<List<double>> list = new List<List<double>>();
var list1 = new List<double>();
list1.Add(1);
list1.Add(2);
var list2 = new List<double>();
list2.Add(3);
list2.Add(4);
list.Add(list1);
list.Add(list2);
var element = list[1][1];
The value of element will be the element of the second list at index of 1.
In this case, 4.
Thats about it:
List<double>[] arrayOfLists = new List<double>[200];
arrayOfLists[0] = new List<double>();
arrayOfLists[0].Add(5);
Console.WriteLine(arrayOfLists[0][0]);
Yes, just make either an array of lists (if you want it fixed sized), or a list of lists.
List<List<double>> items = new List<List<double>>();
List<double> close = new List<double>()
items.Add(close); //close is now element 0 in the outer list.
close.Add(1.23);
double result = items[0][0]; //result now equals 1.23

Create an int[] from Dictionary<int, List<int>>, from each dictionary element's Value List<int> I need an array which contains all dictionary elements

The solution I have for now is as...
Dictionary<int, List<int>> oDict = <Some code to fill in the dictionary>;
var oList = new List<int>();
oDict.Values.ForEach(oList.AddRange);
oList.ToArray();
Is there a way to do this without using the additional List<int>?
Yup, that looks like:
var array = oDict.Values.SelectMany(list => list).ToArray();
(If you only want distinct elements, just call Distinct before ToArray.)

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();

Categories