【问题标题】:Swap List<> elements with c# using LINQ使用 LINQ 与 c# 交换 List<> 元素
【发布时间】:2009-07-10 17:51:58
【问题描述】:

我有这份清单

var list = new List { 3, 1, 0, 5 };

我想将元素 0 与 2 交换

输出 0、1、3、5

【问题讨论】:

标签: c# linq


【解决方案1】:

如果您只想对其进行排序,我会使用 List.Sort()。

如果你想交换,没有内置的方法可以做到这一点。不过,编写扩展方法会很容易:

static void Swap<T>(this List<T> list, int index1, int index2)
{
     T temp = list[index1];
     list[index1] = list[index2];
     list[index2] = temp;
}

你可以这样做:

list.Swap(0,2);

【讨论】:

  • 你打败了我!我仍然会返回一个 IEnumerable。
  • 您无法按索引访问 IEnumerable,因此您的方法将不起作用。您可以返回一个 IEnumerable,但除非您构造一个副本,否则这可能是意外的行为,因为您将返回修改后的集合。构建副本会增加开销。
  • 您可以使用 Enumerable.ElementAt 按索引访问 IEnumerable。
  • @Joe Chung:但这并不是“真正”使用 IEnumerable - 它是通过枚举流来获取某个位置的元素,这非常低效。
  • @ReedCopsey 您应该将其设为 IList 扩展,然后它也适用于 ObservableCollection 等。
【解决方案2】:

经典交换是...


int temp = list[0];
list[0] = list[2];
list[2] = temp;

如果您正在寻找,我认为 Linq 没有任何“交换”功能。

【讨论】:

    【解决方案3】:

    如果某些东西不被直接支持......让它成为第一!

    看看"extension methods"的概念。有了这个,您可以轻松地使您的列表支持 Swap() 的概念(这适用于您想要扩展类的功能的任何时候)。

        namespace ExtensionMethods
        {
            //static class
            public static class MyExtensions 
            {
                //static method with the first parameter being the object you are extending 
                //the return type being the type you are extending
                public static List<int> Swap(this List<int> list, 
                    int firstIndex, 
                    int secondIndex) 
    
                {
                    int temp = list[firstIndex];
                    list[firstIndex] = list[secondIndex];
                    list[secondIndex] = temp;
    
                    return list;
                }
            }   
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-23
      • 2011-10-29
      • 1970-01-01
      • 2013-05-30
      • 2010-10-25
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      相关资源
      最近更新 更多