如果除了foreach循环和新的集合创建之外还有任何简短的方法在现有List中的特定对象之后添加对象?
举个例子:
"艾米","杰里","贝","艾米","杰克".我希望在每个"amy"之后添加"simon"
Dar*_*ung 11
如果您知道要输入项目的位置,则可以执行此操作
List.Insert(position, item)
Run Code Online (Sandbox Code Playgroud)
您可以使用Linq执行此操作.
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");
}
Run Code Online (Sandbox Code Playgroud)
使用foreach但您可以将其放入扩展方法以保持代码清晰.
您可以轻松地将其放入扩展方法中.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在来电:
List<String> list = new List<String>() { "amy","jerry","tony","amy","jack" };
list.AddAfterEach(p => p == "amy", "simon");
Run Code Online (Sandbox Code Playgroud)
您必须使用List中的Insert(int index,T item)将元素添加到指定索引处的List中.如果index等于Count,则将item添加到List的末尾.该方法是O(n)操作,其中n是Count.