通过类的ObservableCollection迭代

时间:2017-12-07 08:20:02

标签: c# uwp

我使用ObservableCollection.Class为类分配值包含MainItems及它的SubItems。现在我如何读取MainItem的每个输入的所有SubItem?

 public class MainItems
   {
    public string ItemName { get; set; }
    public ObservableCollection<SubItems> SubItemsList { get; set; }
   }
   public class SubItems
   {
    public string SubItemName { get; set; }
   }

  ObservableCollection<MainItems> _data = new   ObservableCollection<MainItems>();
        for (int i = 1; i <= 5; i++)
        {
            MainItems _mainItems = new MainItems();
            _mainItems.ItemName = "Main" + i.ToString();
            _mainItems.SubItemsList = new ObservableCollection<SubItems>();
            for (int j = 1; j <= 3; j++)
            {
                SubItems _subItems = new SubItems()
                {
                    SubItemName = "SubItem" + i.ToString()
                };
                _mainItems.SubItemsList.Add(_subItems);
            }
            _data.Add(_mainItems);
        }

2 个答案:

答案 0 :(得分:2)

foreach循环总是尊重集合(列表,数组,字典(特殊),...)边界并迭代所有元素,因此它是实现所需内容的最短途径。它不允许您从当前迭代的集合中添加/删除元素。在这种情况下,经典for循环是你的朋友。

Microsoft的完整说明: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in

根据Fangs评论:

// foreach Version
foreach (MainItems mainItem in _data)
{
    foreach (SubItems subItems in mainItem.SubItemsList)
    {
        Console.WriteLine($"{mainItem.ItemName} has a child {subItems.SubItemName}!");
    }
}

// for Version
for (int i = 0; i < _data.Count; i++)
{
    MainItems mainItem = _data[i];
    for (int k = 0; k < mainItem.SubItemsList.Count; k++)
    {
        SubItems subItem = mainItem.SubItemsList[k];
        Console.WriteLine($"{mainItem.ItemName} has a child {subItem.SubItemName}!");
    }
}

答案 1 :(得分:0)

//对于枚举器版本

//获取输入主项目

string input = "Main1";

    IEnumerable<ObservableCollection<SubItems>> ItemsforSelectedMainIem = _data.Where(x => x.ItemName == input).Select(x => x.SubItemsList);
    var e = ItemsforSelectedMainIem.GetEnumerator();
    while (e.MoveNext())
    {
        var v = e.Current.Select(x=>x.SubItemName).ToList();
        foreach (var item in v)
        {
            Console.WriteLine(item);
        }
    }