I'm having some issues with my programm in c#.
Basically I have a list called mainList with 3 items in it. First two items are integers, but third one is another list containing more items.
mainList[0] = 8;
mainList[1] = 1;
mainList[2] = list;
By using foreach loop I'm able to print all of those items.
foreach (var i in (dynamic)(mainList[2]))
{
Console.WriteLine(i);
}
However I don't know how to access them. The thing is that I can't use indexes, because it is not an array. I would like to do something like this:
foreach (var i in (dynamic)(mainList[2]))
{
// First item is in datetime type, so I would like to change it to int
Console.WriteLine(Convert.ToInt64(i[1]));
}
Is there a way to access items inside list like we do it in arrays with a help of indexes?
Lists support the same index-based access as arrays, so you can use
mainList[n]
to access the nth entry in mainList.
I guess you are looking for something like this, although it is really unclear what you're asking:
foreach(var item in mainList)
{
if(item is System.Collections.IEnumerable)
{
foreach(var obj in ((System.Collections.IEnumerable)item))
{
Console.WriteLine(obj);
}
}
}
Related
I have a List of Items and a List of ItemsContainer which is a class that holds items.
all the items are unique
every item is located in at most one ItemContainer
the ItemContainer support only: Remove(Item) and Contains(Item) methods
I would like to remove all the items in my list from all the itemContainers.
right now I'm thinking of doing something like that:
List<ItemContainer> itemContainerList = ...
List<Item> itemsList = ...
foreach (ItemContainer itemContainer in itemContainerList)
{
foreach (Item item in itemsList)
{
if (itemContainer.Contains(item))
{
itemContainer.Remove(item);
}
}
}
Hoping to make this more efficient and elegant.
Thanks,
Aviram.
Following on from further information being unveiled, I've found that the constraints mean that any of the "conventionally efficient" ways of doing it aren't applicable.
Based on your constraints, I can only suggest flipping the loops:
foreach (Item item in itemsList)
{
foreach (ItemContainer itemContainer in itemContainerList)
{
if (itemContainer.Contains(item))
{
itemContainer.Remove(item);
break;
}
}
}
It's still not ideal, due to the unfortunate prior existing issues of your set-up, but it'll be slightly quicker by virtue of only going through the items once.
I'm trying to add new elements to a list of lists while iterating over it
List<List<String>> sets = new List<List<string>>();
foreach (List<String> list in sets)
{
foreach (String c in X)
{
List<String> newSet = ir_a(list, c, productions);
if (newSet.Count > 0)
{
sets.Add(newSet);
}
}
}
The error I get after a few loops is this:
Collection was modified; enumeration operation may not execute
I know the error is caused by modifying the list, so my question is: What's the best or most fancy way to sort this thing out?
Thanks
You might get away with this in other languages but not C#. They do this to avoid funny runtime behaviour that isn't obvious. I prefer to set up a new list of things you are going to add, populate it, and then insert it after the loop.
public class IntDoubler
{
List<int> ints;
public void DoubleUp()
{
//list to store elements to be added
List<int> inserts = new List<int>();
//foreach int, add one twice as large
foreach (var insert in ints)
{
inserts.Add(insert*2);
}
//attach the new list to the end of the old one
ints.AddRange(inserts);
}
}
Imagine that if you had a foreach loop, and you added an element to it each time, then it would never end!
Hope this helps.
Is there a property or a method on the CheckBoxList class that will return an array of ints that represents all of the selected indexes? This is in ASP.NET.
According to the MSDN documentation, there doesn't appear to be. You'll have to iterate the items yourself.
Here is a method that does just that. It iterates each item, checks if it is selected, then adds the index to a list. I use a list because a list is mutable whereas an array is not. Then to return an array, I just call ToArray() on the list.
public int[] selectedIndexesOfCheckBoxList(CheckBoxList chkList)
{
List<int> selectedIndexes = new List<int>();
foreach (ListItem item in chkList.Items)
{
if (item.Selected)
{
selectedIndexes.Add(chkList.Items.IndexOf(item));
}
}
return selectedIndexes.ToArray();
}
You could create an extension method to simulate the behavior you want. The benefit of that being that you could re-use it on any list control. Below is a rough example (I'm just returning the list of strings of the values, you could return anything though, the index, the value, the entire list item, etc.).
public static List<string> SelectedValues(this ListControl lst)
{
List<string> returnLst = new List<string>();
foreach (ListItem li in lst.Items)
{
if (li.Selected == true)
{
returnLst.Add(li.Value);
}
return returnLst;
}
I have a c# wpf listbox and I am trying to get the values from the selected items. I cannot use a foreach loop (every value I find will remove an item from the listbox). But this seems impossible.
What I want is somthing like this:
for (int i = <numberofselecteditems> - 1; i >= 0; i--)
{
string displaymembervalue = listbox.selecteditem[i].displaymembervalue;
}
I have a solution which involve to loop over all the listbox items twice. This is not really an option since it will slow the app too much.
Like I said before, this is NOT the
System.Windows.Forms.Listbox
but the
System.Windows.Controls.Listbox
thank you!!
J.
See the solution here, it is essentially using a foreach in the follolwing fashion:
foreach (var item in listBox1.SelectedItems)
{
// Do what you want here... Console.WriteLine(item), etc.
}
If you really want to do it with a for loop rather than a foreach, then do the following:
for(int i = selectedItems.Count - 1; i >= 0; --i)
{
var item = selectedItems[i];
// Do what you want with item
}
Here is your XAML bound to a Observable collection
<ListBox ItemsSource="{Binding items}"/>
Here is your observable collection of objects
private ObservableCollection<Object> _items;
public ObservableCollection<Object> items{
get{ return _items; }
}
Here is the enumeration over them and the removing of each item
for(int x = 0; x < _items.Count; x++){
_items.Remove(_items.Where(n => n == _items[x]).Single());
//You may have to do a notify property changed on this if the UI Doesnt update but thats easily googled.
//Traditionally it would update. However since you are bound to items Im not sure if it will update when you manipulate _items
}
Create a second list. You still have to iterate twice, but the second iteration is not over the entire list of items.
var items List<ListBoxItem>;
foreach (var item in listbox1.SelectedItems)
items.Add(item);
foreach (var item in items)
listbox1.Remove(item);
Alternatively instead of enumerating twice you can create a copy of the list of objects and then remove the items from the original list while still enumerating.
foreach (var selectedItem in listBox1.SelectedItems.Cast<List>())
{
//remove items from the original list here
}
G'day all,
Is there a way to preform projection on the contents of a list box.
Specifically I'd like to be able to do it without having to clear and add back the contents of my listbox
This is what I currently have.
public static void SetSelectedWhere(this ListBox listbox, Func<ListItem,bool> condition)
{
var queryableList = listbox.Items.Cast<ListItem>();
queryableList.Select(x=>condition(x)?x.Selected:x.Selected=false);
listbox.Items.Clear();
listbox.Items.AddRange(queryableList.ToArray<ListItem>());
}
and it seems silly to have to clear out my existing collection and add the contents back.
Any thoughts
What about plain old iteration?
foreach (ListItem item in listbox.Items)
{
item.Selected = condition(item);
}
LINQ is not the answer to life the universe and everything. Particularly that part of the universe that involves setting properties on existing objects.
listbox.Items
.Cast<ListItem>()
.Where(x=> condition(x))
.ToList()
.ForEach(item => item.Selected = true);
List<T> has a method called ForEach and you can perform an action for any of the items in the list:
http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx
It is silly to remove and read the items in the collection since it is completely unnecessary.
You should be able to simplify it to the following:
foreach (ListItem item in listbox.Items)) {
item.Selected = condition(item);
}