I have an IEnumerable object as:
IEnumerable<string> listSelectedItems;
Which contains three items. Now i created a new object and want to get all items from listSelectedItems, so i wrote this code:
IEnumerable<string> newList = listSelectedItems;
But now when i alter newList, the listSelectedItems also gets altered. How can i achieve altering or creating a new IEnumerable without refernce.
Are you looking for this?
IEnumerable<string> newList = listSelectedItems.ToList();
IEnumerable is an interface, so you can't instantiate it, you need an implementation of it, for example List
IEnumerable<string> newList = new List<string>(listSelectedItems);
In your case setting newList = listSelectedItems means that newList will be just a reference to the listSelectedItems so if the underlying object is changed, newList will reference the changed object.
Related
How do I create an IReadOnlyList<string> with some values in it?
I found an example of ReadOnlyCollection which seems to convert an existing collection to an ReadOnlyCollection but that approach didn't work.
Here's what I tried:
var myList = new List<string>()
{
"Hello World!",
"Some more text here"
};
var myReadOnlyList = new IReadOnlyList<string>(myList);
I also tried adding my string values into an IReadOnlyList<string> during declaration but that didn't work either.
What's the right way to create a IReadOnlyList<string>() with some values in it?
IReadOnlyList<string>, despite the name, just means "list you can read", it doesn't mean "immutable list". Whether the list is immutable depends on the concrete class that will end up implementing the interface.
Therefore, what you should do depends on your needs.
IReadOnlyList<string> myReadOnlyList = myList;. This works because List<string> implements IReadOnlyList<string>. It does not prevent others from casting myReadOnlyList back to List<string>.
IReadOnlyList<string> myReadOnlyList = myList.AsReadOnly();. This creates a read-only proxy for the original list. Although it does prevent others from casting myReadOnlyList back to List<string>, the contents of myReadOnlyList may still change as a result of modifications on myList.
IReadOnlyList<string> myReadOnlyList = ImmutableList.CreateRange(myList); This creates an ImmutableList<string> which contains copies of the original list's contents and does not allow any modification. Changes to myList won't be visible in myReadOnlyList.
Try this:
List<string> listData = new List<string>();
public IReadOnlyList<string> readOnlyData = listData.AsReadOnly();
And here's an example on how to use it:
string text = readOnlyData[0];
Note: Make sure that you add to listData before you assign it to readOnlyData.
I am writing a c# console program.
I have a function that returns a list of objects.
e.g the following will return a list of objects.
p.getList();
If I already know the index of the object I want to reference from the list, then how to I access this?
For example I want to do the following which obviously is incorrect:
p.getList()[Index]
This would give me the item in the list at index.
To get around this I have done the following:
List<MyObject> mylist = p.getList();
mylist[Index];
but the above seems inefficient, to have to create a copy just to reference a value.
Any tips on how I can access?
Thanks.
If you don't want the list, but an item and you know the Index then
var item = p.getList()[Index];
syntax is perfectly correct. Please, notice, that List<T> is a reference type, that's why in case of
var list = p.getList(); // reference copy, not the collection cloning
var item = list[Index];
...
var otherItem = list[otherIndex];
the var list = p.getList(); adds a miniscule overhead: it's reference, not the entire collection is being copied.
Hi I have a list of objects(list1) and I'd like to make a copy of this list but I want that the objects in the second list(list2) to not be linked to the one in first list.
this is what I do
list<Obj> list1 = new list<Obj>{};
// I fill the list1 with objects Obj
// now I want to make a deep copy this is what I do
list<Obj> list2 = new list<Obj>(list1);
// but when I edit an object in list 1 I also edit the object in list2
I'd like to be able to edit the objects in list1 without edititng the object in list2,how can I get that???
thanks for your answers
You should implement the ICloneable interface in your Obj class. After that, you can call this code to create your second list:
list<Obj> list2 = new list<Obj>(list1.Select(x => x?.Clone()));
It will clone every item in the list. (With null-check)
You could add a copy constructor to your Obj.
Then loop through list1 create a new instance of your objects using the copy constructor and add it to list2.
Example:
Copy constructor:
public Obj(Obj copyFrom)
{
this.field1 = copyFrom.field1;
.
.
}
With the following LINQ query you have a one liner to use the above contructor:
list2.AddRange(list1.Select(s => new Obj(s)));
I want to convert the items entered to a String list to:
System.Collections.ObjectModel.ReadOnlyCollection<string>
I have tried using:
(System.Collections.ObjectModel.ReadOnlyCollection<string>)listname
But it returns an error.
You can create a new instance using the existing List in the constructor.
var readOnlyList = new ReadOnlyCollection<string>(existingList);
ReadOnlyCollection(Of T) Constructor on MSDN
If you've got:
List<string> names=new List<string>(){"Rod", "Jane", "Freddy"};
Then you can say:
ReadOnlyCollection<string> readOnlyNames=names.AsReadOnly();
This doesn't copy the list. Instead the readonly collection stores a reference to the original list and prohibits changing it. However, if you modify the underlying list via names then the readOnlyNames will also change, so it's best to discard the writable instance if you can.
The constructor of ReadOnlyCollection accepts an IList
Here is some reference http://msdn.microsoft.com/en-us/library/ms132476.aspx
var myreadonlycollection = new ReadOnlyCollection<string>(listname);
var readonlyCollection = new ReadOnlyCollection<string>(list);
The other answers are correct in that you need to pass an IList<T> to the constructor of a ReadOnlyCollection<T>.
I find it useful to have an extension method on IEnumerable<T> that facilitates the creation of the ReadOnlyCollection<T>:
public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(
this IEnumerable<T> source)
{
if (source == null) throw new ArgumentNullException("source");
return new ReadOnlyCollection<T>(
source as IList<T> ?? source.ToList());
}
I have to declare a list and use it in my code.How ever the number of elements that i will add to list will vary during each time I run my code.So how can I create a list and add elements to it dynamically with out specifying its size during declaration?
var myList = new List<string>();
myList.Add("foo");
myList.Add("blah");
// and on and on ...
List's in .Net will automatically resize themselves as you add to them.
You don't have to specify the bounds of a list (as you do with arrays). You can keep on calling Add() method to add elements in the list. You can create either a generic list which takes only specified types of objects and a non-generic list that only takes objects:
Generic:
List<int> intList = new List<int>();
intList.Add(10);
intList.Add(20);
Non-Generic:
ArrayList objList = new ArrayList();
objList.Add(New Employee());
objList.Add(20);
objList.Add("string");
The later can take any type of object but is not type-safe.
The System.Collection namespace is full of collection classes that can dynamically contract and expand its size, see the Generic namespace for the most used classes: http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx
I recommend sticking with a List if you doubt what you are doing:
var list = new List<string>();
list.Add("test1");
list.Add("test2");
list.Remove("test1");