交换 List<T> 中的两个项目 [英] Swap two items in List&lt;T&gt;

查看:36
本文介绍了交换 List<T> 中的两个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有 LINQ 方法来交换 List 中两个项目的位置?

Is there a LINQ way to swap the position of two items inside a List<T>?

推荐答案

检查来自 C#:Swap 方法的良好/最佳实现.

public static void Swap<T>(IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
}

可以像 linq-i-fied 一样

which can be linq-i-fied like

public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
    return list;
}

<小时>

var lst = new List<int>() { 8, 3, 2, 4 };
lst = lst.Swap(1, 2);

这篇关于交换 List<T> 中的两个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆