【问题标题】:Order by list using count c#使用count c#按列表排序
【发布时间】:2017-02-13 20:56:04
【问题描述】:

我有一个物品清单

row_id,项目

12134,项目 X

13243,项目 Y

在 C# 中可以根据列表项自动生成 row_id 吗?所以列表的输出不是 12134 和 13243,而是

row_id,项目

1,项目 X

2,项目 Y

【问题讨论】:

  • 使用 for 循环并给出索引 + 项目作为输出
  • 为什么不在数据库中使用自动生成的列?

标签: c#


【解决方案1】:
var source = new List<Item> {new Item(12134, "Item X"), new Item(13243, "Item Y")};
var dest = source.OrderBy(item => item.row_id).Select((item, index) => new Item(index + 1, item.Items)).ToList();

【讨论】:

    【解决方案2】:

    您可以使用 Select 的覆盖将列表项与其列表位置配对,该覆盖采用 (index, item) 对:

    var itemsWithIndex = myList
        // If you would like to change the order of auto-generated IDs,
        // change the expression inside OrderBy; This step is optional.
        .OrderBy(item => <some-expression>)
        .Select((item, index) => new { Item=item, NewId=index+1});
    

    现在您可以根据需要使用项目的索引:显示它,将其设置回项目中,等等:

    foreach (var pair in itemsWithIndex) {
        Console.WriteLine("{0} : {1}", pair.Index, pair.Item.Items);
    }
    

    【讨论】:

      【解决方案3】:

      您可以对列表进行排序、遍历项目并设置每个项目的 ID。

      【讨论】:

        【解决方案4】:
         for(int i = 0; i < items.Count; i++)
            {
                items[i].RowId = i + 1;
            }
        

        这是假设您的项目有一个名为 RowId 的属性。这更简单,不需要使用您可能不了解的 LINQ。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-10-29
          • 2012-01-09
          • 1970-01-01
          • 2021-02-12
          • 2017-07-21
          • 2011-07-24
          • 2021-05-05
          相关资源
          最近更新 更多