本文介绍了在列表中逐项添加项目的快捷方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了foreach循环和新集合创建之外,是否还有其他方法可以在现有List中的特定对象之后添加对象?

If there any short way besides foreach loop and new collection creation to add object after specific object in existing List ?

只是一个例子:

"amy","jerry","tony","amy","jack".我想以简短的方式在每个"amy"之后添加"simon"

"amy","jerry","tony","amy","jack".I want to add "simon" after each "amy" in short way

推荐答案

您可以使用Linq来做到这一点.

You can use Linq to do this.

foreach (var item in values
          .Select((o, i) => new { Value = o, Index = i })
          .Where(p => p.Value == "amy")
          .OrderByDescending(p => p.Index))
{
    if (item.Index + 1 == values.Count) values.Add("simon");
    else values.Insert(item.Index + 1, "simon");
}

使用foreach,但您可以将其放入扩展方法中以保持代码清晰.

Uses a foreach but you can put it into a extension method to keep the code clear.

您可以轻松地将其放入扩展方法中.

You can easily put this into a extension method.

public static void AddAfterEach<T>(this List<T> list, Func<T, Boolean> condition, T objectToAdd)
{
    foreach (var item in list.Select((o, i) => new { Value = o, Index = i }).Where(p => condition(p.Value)).OrderByDescending(p => p.Index))
    {
        if (item.Index + 1 == list.Count) list.Add(objectToAdd);
        else list.Insert(item.Index + 1, objectToAdd);
    }
}

现在通话:

List<String> list = new List<String>() { "amy","jerry","tony","amy","jack" };
list.AddAfterEach(p => p == "amy", "simon");

这篇关于在列表中逐项添加项目的快捷方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 00:13