【问题标题】:How to select two atributes of list for a List of int如何为 int 列表选择列表的两个属性
【发布时间】:2021-06-19 01:46:21
【问题描述】:

我想为一个 List 获取两个 int 属性:

我试试:

            List<int> idsAgrupados = listMain.Select(x => new { x.productID, x.personalID}).Cast<int>().ToList();

但是这样我得到一个转换错误。

【问题讨论】:

  • 在您的 Linq 中,它返回 List of anonymous type(它是一个对象),但您将变量声明为 List&lt;int?&gt; 类型。您的变量应该会收到 List 类型的结果。
  • 我用 Cast 编辑了 aswer,但这样我得到一个转换错误。
  • @YongShun 所以我不知道怎么做,我只是把我试过的东西放了
  • 嗨@joeyanthon,您的更新代码Cast 也会抛出强制转换异常。您能否在问题中提供示例输入和预期输出。谢谢。
  • 应该是 : ((x.productID & 0xFFFF)

标签: c# linq lambda


【解决方案1】:

你可以这样使用:

        List<int> firstList = data.Select(x => x.firstId).ToList();
        List<int> secondList = data.Select(x => x.secondId).ToList();

        List<List<int>> g = new List<List<int>>()
        {
            firstList,
            secondList
        };

【讨论】:

  • 你在哪里将选定的属性转换为整数?
【解决方案2】:

如果要转换 lambda 选择中的所有属性,请单独转换每个项目。

List<int> idsAgrupados = listMain.Select(x => new { productID = Convert.ToInt32(x.productID), personalID = Convert.ToInt32(x.personalID) }).ToList();

如果您在这方面遇到任何错误,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 2021-09-13
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多