Is there a way to access the objects in the list? like, getting an exact field in a particular object. For Instance:
List<Object> allObjectResult = new List<Object>();
allObjectResult.AddRange(method(ObjectOne.ToArray()));
allObjectResult.AddRange(method(ObjectTwo.ToArray()));
allObjectResult.AddRange(method(ObjectThree.ToArray()));
I want to get a particular field in ObjectOne, ObjectTwo and ObjectThree. How am I able to do that?
Updated Question
In List we can access elements position by order. My first attempt in getting the a particular value in an object inside a List works. This is what I did:
Create a new instance of a list:
List<Object> objList = new List<Object>();
Added data on it:
objList.Add(objdata);
Use it in a method:
Object[] result = binding.method(Object.ToArray());
Loop through:
for(i = 0; i < result.Length; i++)
{
Console.WriteLine("objs {0} - {1}", objList[i].Name, result[i].id);
}
However, What I want is I have three objects. What I did is added them in a List:
List<Object> allObjectResult = new List<Object>();
allObjectResult.AddRange(binding.method(ObjectOneList.ToArray()));
allObjectResult.AddRange(binding.method(ObjectTwoList.ToArray()));
allObjectResult.AddRange(binding.method(ObjectThreeList.ToArray()));
I want to do the same thing like what I did in getting a name in an object (anyway, it's an object within a List). I want them to access using a loop.
Select objects of a certain type:
foreach (var obj1 in allObjectResult.OfType<ObjectOne>()) {
Console.WriteLine(obj1.Whatever);
}
Check the type dynamically:
foreach (var obj in allObjectResult) {
if (obj is ObjectOne) {
var obj1 = (ObjectOne)obj;
Console.WriteLine(obj1.Whatever);
} // else ...
}
Related
So i have an object of ojects like so
[["value1","value2","value3"]]
and my goal is to access these objects, and modify them, then return it to a new list containing the existing objects.
Here's what I've tried
List<dynamic> data = new List<dynamic>();
foreach(var i in objects)
{
List<dynamic> innerData = new List<dynamic>();
foreach(var j in i)
{
innerData.Add(j + " NEW");
}
data.AddRange(innerData);
}
the output isn't the same. It will return the following
[["value1 NEW"], ["value2 NEW"],["value3 NEW"]]
It returns a new list, but instead of having one object with three values inside the list, it returns three objects with one value inside the list.
My goal is to have the same output format as the input format. Like so
[["value1 NEW","value2 NEW", "value3 NEW"]]
As already suggested in the comments you need to use Add instead of AddRange. AddRange adds each element of a list as a new element in the outer list and what you want is add the inner list as one element of the outer list.
The fixed code then looks like this:
List<dynamic> data = new List<dynamic>();
foreach(var i in objects)
{
List<dynamic> innerData = new List<dynamic>();
foreach(var j in i)
{
innerData.Add(j + " NEW");
}
data.Add(innerData);
}
ObservableCollection<TypeA> TempList = ObservableCollection<TypeA>();
List<TypeB> FullValues = listB;
Count = intA;
foreach (var ListA in AllList)
{
for (var i = 1; i < Count; i++)
{
ListA.Name = FullValues[i].Name;
ListA.Surname = FullValues[i].Surname;
ListA.Amount = FullValues[i].Amount;
ListA.Address = FullValues[i].Address;
ListA.Source = FullValues[i].Source;
ListA.OrderCreationDate = FullValues[i].Date;
ListA.Type = FullValues[i].Date;
ListA.Commerce = FullValues[i].Commerce;
TempList.Add(ListA);
}
}
Hello, I'm using an ObservableCollection of a specific type to be filled by a local variable of the same type but using the Add method adds the new object and overwrites the preceding.
I need to add values to the same object but more than one time. So i am using an ObservableCollection to store the values more than time
Tried with List and ObservableCollection
Expected Result: The list for example contains 3 values with
ListA[0], ListA[1], ListA[2]
Actual Result:
ListA[2], [2], [2]
Thank you for your help
Edited: I tried to add another case of the issue, this may look dumb but i need to duplicate the main object to add other values to them and keep them within the same list and as someone said, i am still using the same object thats why it is not changing:
List<string> RoadType = List<string>();
RoadType = somevalues;
foreach(var roads in listofroads)
{
roads.street = "xxxxx"
roads.country= "xxxxx"
//I want to duplicate roads twice
TestList.Add(roads);
TestList.Add(roads);
count = 0;
//Changing the properties of the object
foreach(var newroads in TestList)
{
roads.street = RoadType[i].street;
roads.country = RoadType[i].country;
count++
MainRoadList.Add(newroads);
}
MainRoadList.Add(roads);
}
This question already has answers here:
Why does adding a new value to list<> overwrite previous values in the list<>
(2 answers)
Closed 4 years ago.
I have a code block similar to this:
List<Object> returnObjDataLine = new List<object>();
foreach (var tuple in dataPerTime)
{
returnObjDataLine.Clear();
returnObjDataLine.Add(tuple.Item1);
foreach (var line in PlotLines)
{
if (tuple.Item2.Equals(line.Key))
{
returnObjDataLine.Add(tuple.Item3);
}
else
{
returnObjDataLine.Add(null);
}
}
returnObjData.Add(returnObjDataLine);
}
However the Clear() method clears out the data already added to the returnObjData Dictionary, sort of. If there are 10,000 tuples, then after the loop runs the returnObjData will contain 10,000 instances of the very last data piece added (Clear() is not called after the last iteration).
If I modify the code to create a new List each iteration:
foreach (var tuple in dataPerTime)
{
List<Object> returnObjDataLine = new List<object>();
returnObjDataLine.Add(tuple.Item1);
foreach (var line in PlotLines)
{
if (tuple.Item2.Equals(line.Key))
{
returnObjDataLine.Add(tuple.Item3);
}
else
{
returnObjDataLine.Add(null);
}
}
returnObjData.Add(returnObjDataLine);
}
the loading loop works correctly but this seems very expensive as there can be 10s if not 100s of thousands of iterations required. Creating a new object every time seems to be inefficient.
What am I missing with Clear()? Is there some sort of "commit" that needs to be called first?
Looks like what you need to do is have a temporary list and a long term list... Something like this:
List<Object> longTermObjects = new List<object>();
foreach (var tuple in dataPerTime)
{
List<Object> returnObjDataLine = new List<Object>();
returnObjDataLine.Add(tuple.Item1);
foreach (var line in PlotLines)
{
if (tuple.Item2.Equals(line.Key))
{
returnObjDataLine.Add(tuple.Item3);
}
else
{
returnObjDataLine.Add(null);
}
}
longTermObjects.Add(returnObjDataLine);
}
This will give you a clean returnObjDataLine each iteration without removing the referenced items in longTermObjects.
Edit To Add Reference Type Information:
By default .NET will store 1 copy of an object into memory, and then "reference" that object anywhere you use it. Take the following example:
int A = 1;
int B = A;
Console.WriteLine($"A = {A}");
Console.WriteLine($"B = {B}");
A = 0;
Console.WriteLine($"A = {A}");
Console.WriteLine($"B = {B}");
Result:
A = 1
B = 1
A = 0
B = 0
Why you ask does B = 0 on the 4th line? Because B had a REFERENCE to A, it didn't contain the actual VALUE of A, so when A changed, B changed as well.
If I wanted B to contain only the value of A then I would need a way to create a new "value" instead of a reference. The way you do this varies for each type of object. One way and probably not the best would be something like:
int B = int.Parse(A.ToString());
Which would convert A to a string representing the value of A and then into a new int with the Parse. Now I have the value stored in B instead of just a reference.
If I wanted to do the same thing with a table of objects then I would have to do something like this:
List<MyObject> oldList = new List<MyObject>();
//Put some objects into oldList
List<MyObject> newList = oldList.Select(x => new MyObject(x.Param1, x.Param2)).ToList();
In this example I am basically taking each object in oldList and creating a new MyObject which is then put into newList.
I have a code similar to this
List<string> list = new List<string>();
for (int i = 0; i < 1000; i++)
{
list.Add(Guid.NewGuid().ToString());
}
foreach (var item in list)
{
lit.Text += string.Format("<p>{0}</p>", item);
}
Session["VarList"] = list;
ViewState["VarList"] = list;
list.Clear();
This might sound like a duplicate to this How to preserve lists already created before using List.Clear() but i need to save that list somehow beacuse my list is is being populated on various methods and i am facing outofmemoryexception. My list contains object a class and that class has a list, DataTable and some properties. Any solution will be very much appreciated i just need this functionality of preserving the data and clearing the list.
Sample for storing a dictionary in session (not direct answer):
List<MyObject> Mylist;
MyList = GetObjects(TheDate);
Dictionary<DateTime> myDictionary = new Dictionary<DateTime>();
myDictionary[TheDate] = MyList;
Session["DateCollections"] = myDictionary;
Sample for retrieving from session (should have null check to be sure it's there):
Dictionary<DateTime> myDictionary = (Dictionary<DateTime>) Session["DateCollections"];
I hope you can continue with this or at least get some inspiration :)
I have a collection of type object called MHP. MHP has multiple member fields(Name, AC, Par_ID, etc).
I create a List;
private List<MHP> mhpList = new List<MHP>();
public List<MHP> MHPList
{ get { return mhpList; } set { mhpList = value; } }
And I populate a portion of the fields with values in a for loop by creating a new object:
mhpList.Add(new MHP
{
MHP_Name = something,
MHP_AC = a number
});
Now I want to populate the remaining field with a value and I’m doing so by creating a new object, but this obviously places the value in a new index of the collection;
mhpList[0] MHP_Name = ‘Something’, MHP_AC = ‘#’, MHP_ParId = null.
mhpList[1] MHP_Name = null, MHP_AC = null, MHP_ParID = ‘something’
I’ve tried creating a new list and adding a new object to that list then using the following to add the new list to mhpList:
mhpList.AddRange(newList)
as wellas and mhp.InsertRange, but each time this add a new index of the object in the collection. How do I add values to unpopulated fields within the SAME index of a collection?
Just access the item using it's index:
mhpList = new List<MHP>();
mhpList.Add(new MHP
{
MHP_Name = something,
MHP_AC = a number
});
mhpList[0].MHP_ParId= "Something";
mhpList[0].MHP_ParID = something;
In more detail, you should use methods of your MHP object, not method of the List. All the list knows is there are some MHP objects in it. What a list can do is:
Add a MHP to the list
Remove a MHP from the list
Fetch a MHP from the list
If you want to change the fields inside a specific MHP, that's not something concerned with the list, but with MHP objects. You fetch the object, and then modify it. Then, if it's a reference object (class) you're done. If it's a value object (struct), you must re-add it to the list, like:
MHP obj = mhpList[0];
obj.MHP_ParID = something;
mhpList[0] = obj;