这是正确的迭代方法

本文关键字:迭代 方法 | 更新日期: 2023-09-27 18:08:36

我有一个以分号分隔的字符串列表。

总是有一个偶数,因为第一个是键,下一个是值,

,

name;Milo;site;stackoverflow;

所以我把它们分开了:

 var strList = settings.Split(';').ToList();

但是现在我想使用foreach循环将这些放入List<ListItem>

我想知道它是否可以通过迭代完成,或者如果我必须使用一个值'i'来获得[i] and [i+1]

这是正确的迭代方法

可以用LINQ完成,但我不确定这个更好

var dict = input.Split(';')
            .Select((s, i) => new { s, i })
            .GroupBy(x => x.i / 2)
            .ToDictionary(x => x.First().s, x => x.Last().s);

你也可以使用moreLinq的批处理

var dict2 = input.Split(';')
            .Batch(2)
            .ToDictionary(x=>x.First(),x=>x.Last());

我不能编译这个,但这应该为您工作:

var list = new List<ListItem>();
for (int i = 0; i < strList.Count; i++)
{
    i++;
    var li = new ListItem(strList[i - 1], strList[i]);
    list.Add(li);
}

,我不能完全重现你的环境,但因为第一个是键,第二个是值,而且你确定字符串的状态,这是一个非常简单的算法。

然而,利用foreach循环仍然需要您对索引有更多的了解,因此使用基本的for循环会更直接一些。

首先是我使用的一个有价值的辅助函数。它类似于GroupBy,除了它按顺序索引分组,而不是按某个键分组。

    public static IEnumerable<List<T>> GroupSequential<T>(this IEnumerable<T> source, int groupSize, bool includePartialGroups = true)
    {
        if (groupSize < 1)
            throw new ArgumentOutOfRangeException("groupSize", groupSize, "Must have groupSize >= 1.");
        var group = new List<T>(groupSize);
        foreach (var item in source)
        {
            group.Add(item);
            if (group.Count == groupSize)
            {
                yield return group;
                group = new List<T>(groupSize);
            }
        }
        if (group.Any() && (includePartialGroups || group.Count == groupSize))
            yield return group;
    }

现在您只需执行

var listItems = settings.Split(';')
    .GroupSequential(2, false)
    .Select(group => new ListItem { Key = group[0], Value = group[1] })
    .ToList();

如果你想使用foreach

string key=string.Empty;
    string value=string.Empty;
    bool isStartsWithKey=true;
    var strList = settings.Split(';').ToList()
    foreach(var item in strList)
    {
      if(isStartsWithKey)
      {
        key=item;
      }
      else
      {
        value=item;
        //TODO: now you can use key and value
      }
      isStartsWithKey=!isStartsWithKey;
    }
List<int, string> yourlist;
for(int i=0;i<strList.length/2;i++)
{
  yourlist.add(new ListItem(strList[i*2], strList[i*2+1]));
}

在我看来这是最简单的方法

for(var i = 0; i < strList.Count(); i = i + 2){
    var li = new listItem (strList[i], strList[i + 1];
    listToAdd.Add(li);
}

更新示例

for (var i = 0; i < strList.Count(); i = i + 2){
    if (strList.ContainsKey(i) && strList.ContainsKey(i + 1)){
        listToAdd.Add(new listItem(strList[i], strList[i + 1]);
    }
}