1

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

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

前任:

name;Milo;site;stackoverflow;

所以我把它们分开:

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

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

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

4

6 回答 6

4

可以用 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的 Batch

var dict2 = input.Split(';')
            .Batch(2)
            .ToDictionary(x=>x.First(),x=>x.Last());
于 2013-04-11T17:05:35.730 回答
3

我无法编译它,但这应该适合你:

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循环会更直接一些。

于 2013-04-11T17:02:02.953 回答
1

首先,我使用了一个有价值的辅助函数。它类似于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();
于 2013-04-11T17:09:20.057 回答
0

如果你想使用 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;
    }
于 2013-04-11T17:02:43.413 回答
0
List<int, string> yourlist;
for(int i=0;i<strList.length/2;i++)
{
  yourlist.add(new ListItem(strList[i*2], strList[i*2+1]));
}
于 2013-04-11T17:04:48.803 回答
-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]);
    }
}
于 2013-04-11T17:04:52.857 回答