How update a list in a foreach - c#

I have a foreach of a List and i want to Update the list or (i don´t know wich is better) create a new one with the new values. How to do this ?
My code is bigger than this because i am decrypting, but if help me with this simple, will fix the other.
foreach (Envolvido envolvido in ListaDados.ItemsSource)
{
for (int i = 0; i < ListaDados.ItemsSource.OfType<object>().Count(); i++)
{
var suspid = Convert.FromBase64String(envolvido.SUSPID);
var ivnome = Convert.FromBase64String(envolvido.IVNOME);
}
}
So, with the help of all, i got the correct answer !
List<Envolvido> mylist = t.Result;
for (int index = 0; index < mylist.Count(); index++)
{
var items = mylist.ToList();
Envolvido envolvido = items[index];
envolvido.SUSPID= Convert.FromBase64String(envolvido.SUSPID);
envolvido.IVNOME = Convert.FromBase64String(envolvido.IVNOME);
}
THANKS!

Use for for modifing lists. NOT foreach.
As it says on MSDN:
The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.
List<Envolvido> mylist = t.Result;
for (int index = 0; index < mylist.Count(); index++)
{
var items = mylist.ToList();
Envolvido envolvido = items[index];
envolvido.SUSPID= Convert.FromBase64String(envolvido.SUSPID);
envolvido.IVNOME = Convert.FromBase64String(envolvido.IVNOME);
}

Related

Get listitems according to the index of another list

I have a List<List<string>> with three nested lists. Now I need to check if List[1] equals a certain string and if so, check if the value at this index in List[2] has another certain string. If both conditions return true, then I need to get that certain index and get the item of List[0].
For example:
var list = Titles[0];
var list2 = Titles[1];
var list3 = Titles[2];
foreach (var item in list2)
{
if (item.Contains("Dt."))
{
int idx = list2.IndexOf(item);
var value = list3.ElementAt(idx);
if (value.Contains("25.04.2017"))
{
var newList = list.ElementAt(idx);
}
}
}
This approach doesn't seem very efficient in regards to performance, especially if the nested list contains ~9000 items.
I tried to get the result via lambda expressions first, but I'm not sure if this is the right approach either.
What would be the best or most efficient solution?
Eliminate ElementAt with direct access to index. I believe ElementAt iterates over List in order to get i'th element
Eliminate usage of IndexOf with index provided by for loop I believe IndexOf iterates over List in order to find matching element.
var list = Titles[0];
var list2 = Titles[1];
var list3 = Titles[2];
for (int i = 0 ; i < list2.Count; ++ i)
{
var item = list2[i];
if (item.Contains("Dt."))
{
var value = list3[i];
if (value.Contains("25.04.2017"))
{
var newList = list[i];
}
}
}
Note if size of list2 is greater than size of list or list3 then you potentially get IndexOutOfRangeException
Lambda equivalent for your code:
if(list2.Any(item => item.Contains("Dt.")))
{
int idx = list2.IndexOf("Dt.");
if(list3.ElementAt(idx).Contains("25.04.2017"))
{
var newList = list.ElementAt(idx);
}
}
for (int i = 0; i < list2.Count; ++i)
{
var item = list2[i];
if (item.Contains("Dt."))
{
var value = list3[i];
if (value.Contains("25.04.2017"))
{
var newList = list[i];
break; // Break the loop :-)
}
}
}

Handling multiple lists with if/else condition - recursion

i have many lists which contain 1 or more objects, and if there is more then 1 object in the list, it should do something. When there is only 1 object in the list, then take the second list and do the same. This should happen for 4 lists.
This is my Solution, but i think this is a bad solution. Is there a far better way on handling this code?
if (list1.Count > 1)
for (int i = 0; i < list1.Count; i++)
{
DoSomething(list1);
}
else
{
if (list2.Count > 1)
for (int i = 0; i < list2.Count; i++)
{
DoSomething(list2);
}
else
{
if (list3.Count > 1)
for (int i = 0; i < list3.Count; i++)
{
DoSomething(list3);
}
else
{
...
Many thanks and best regards,
Joerg
// using System.Collections.Generic;
// using System.Linq;
// create an enumerable "list" of your lists (however many there are):
var lists = new[] { list1, list2, list3, … };
// find the first list that has more than 1 element:
var list = lists.FirstOrDefault(_ => _.Count() > 1);
// if there is such a list…
if (list != null)
{
// … then `DoSomething` to each of its items:
foreach (var item in list)
{
DoSomething(item);
}
}
I tried to use same psuedo-code style as OP. The logic replicates the original, but in condensed form and with advantage of easily adding lists to the master list array (as suggested by #Benjamin).
It is assumed that DoSomething is a single function applied to the first list which has Count > 1. If you wanted to apply a custom function per list, you could create another array for holding the function to call for the corresponding list.
listArray = new[] {list1, list2, list3, list4}; // you can add more as needed to this master array
for (int i = 0; i < listArray.Count; i++)
{
if (listArray[i].Count > 1)
{
for (int i = 0; i < listArray.Count; i++)
{
DoSomething(listArray[i]);
}
break; // http://msdn.microsoft.com/en-us/library/adbctzc4.aspx
}
}
You can check first which list you want to use:
var lists = new[]{ list1, list2, list3, list4 };
var list = lists.FirstOrDefault(l => l.Count > 1);
if(list != null)
{
list.ForEach(l => DoSomething(list));
}
Seems like you need the first list for which Count > 1.
Also, inside the for-loop, you're saying DoSomething(list1);. I think it should be DoSomething(list1[i]);
var lists = new [] { list1, list2, list3, list4 };
var target = lists.FirstOrDefault(l => l.Count() > 1);
if (target != null) {
for (int i = 0; i < target.Count; i++)
{
DoSomething(target[i]);
}
} else {
//...
}

Loop through List with Linq condition

The code below works successfully to loop through a List. How do I add a where clause such that only for list items where sType = "File"
for (int i = 0; i < MyGlobals.ListOfItemsToControl.Count; i++) // Loop through List with for
Pseudo Code for what i want
for (int i = 0; i < MyGlobals.ListOfItemsToControl.Count.Where(y => y.sType == "File"); i++) // Loop through List with for
use LINQ to obtain a new filtered List that only contains the items that fit your condition:
var filteredList = MyGlobals.ListOfItemsToControl.Where(i => i.sType == "File").ToList();
for (var i = 0; i < filteredList.Count; i++) // Loop through List with for
...
In addition to sjkm's answer, if you're not using the index, just use a foreach loop.
foreach(var item in MyGlobals.ListOfItemsToControl.Where(i => i.sType == "File"))
{
// Do something with item.
}

Change Key for a SortedList

I need a Sorted list, but after I remove an item from the list I then need to adjust the keys of the other items before adding new items to the list.
You are not allowed to change the key for the items in a "SortedList".
What tool would be best for doing this.
Example code
timedEvQue.Add(3, "First");
timedEvQue.Add(7, "Second");
timedEvQue.Add(9, "Third");
int decAmnt = (int)timedEvQue.Keys[0];
timedEvQue.RemoveAt(0);
for (int i = 0; i < timedEvQue.Count; ++i)
{
timedEvQue.Keys[i] = timedEvQue.Keys[i] - decAmnt; //runtime error here
}
timedEvQue.Add(5, "Forth");
There isn't typically a change key operation for dictionary/hash map type data structures as they would essentially just remove and add the item again. So just remove and add the item back.
timedEvQue.Add(3, "First");
timedEvQue.Add(7, "Second");
timedEvQue.Add(9, "Third");
int decAmnt = (int)timedEvQue.Keys[0];
timedEvQue.RemoveAt(0);
for (int i = 0; i < timedEvQue.Count; ++i)
{
int oldKey = timedEvQue.Keys[i];
string val = timedEvQue[oldKey];
int newKey = oldKey - decAmnt;
timedEvQue.Remove(oldKey);
timedEvQue.Add(newKey, val);
}
timedEvQue.Add(5, "Forth");

Add to array list from listbox selected item does not work properly

I have a program where I am trying to move items from one arrayList to another via a listbox and then print out the info in an XML, but the error I have is when I am adding it often certain times the values would repeat, when there are no repeats.
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
list1.Add(new RandomClass(var1, var2, var3, var4, var5, var6, var7));
foreach (object o in list1)
{
RandomClass m = (RandomClass)o;
selectionBox.Items.Add(m);
}
This is my initialization code.
bool req = true;
if (selectionBox.SelectedItem != null)
{
Count++;
errorLabel.Text = "";
for (int i = 0; i < selectionBox.Items.Count; i++)
{
if (selectionBox.GetSelected(i) == true)
{
RandomClass m = selectionBox.SelectedItem as RandomClass;
if (m.var2 == ((RandomClass)selectionBox.Items[i]).var2)
{
list2.Add(list1[i]);
}
}
}
}
else
{
errorLabel.Text = "Error";
}
Here is where I add to another array list. However as I said often the item would repeat and not be different, how can I resolve this problem?
Try clearing the second list each time you scan and add items from the first list.
list2.Clear();
for (int i = 0; i < selectionBox.Items.Count; i++)
....
I have fixed this problem using a list with my class, and there does not seem to be a problem.
List<RandomClass> list2 = new List<RandomClass>();
And then when adding I just simply put the following in the if statement
list2.Add(m);

Categories