【问题标题】:Selection from List of tuple to List of objects C#从元组列表到对象列表的选择 C#
【发布时间】:2014-03-10 16:41:00
【问题描述】:

在我的 C# 代码中,我有一个列表 List<Tuple<int,string>>。我想选择/将其转换为List<Type>。我想避免迭代我的元组列表并插入其他列表。有没有办法做到这一点?也许使用 LINQ?

【问题讨论】:

  • LINQ 也会迭代,只是没有显示在您的代码中。

标签: c# linq type-conversion tuples


【解决方案1】:

您不能更改列表的类型。您只能创建另一种类型的新列表并用列表中的转换值填充它。我建议使用正是为此目的而存在的List<T>.ConvertAll 方法:

List<Tuple<int, string>> tuples = new List<Tuple<int, string>>();
// ...
List<YourType> types =
     tuples.ConvertAll(t => new YourType { Foo = t.Item1, Bar = t.Item2 });

【讨论】:

    【解决方案2】:

    您没有显示此类型,但我假设它包含 int- 和 string-property:

    List<MyType> result = tupleList
        .Select(t => new MyType { IntProperty = t.Item1, StringProperty = t.Item2 })
        .ToList();
    

    另一种选择:List.ConvertAll:

    List<MyType> result = tupleList.ConvertAll(t => new MyType { IntProperty = t.Item1, StringProperty = t.Item2 });
    

    这假定您的List&lt;Type&gt; 实际上是List&lt;CustomType&gt;(我称之为MyType)。

    我想避免迭代我的元组列表并插入到其他列表中。

    LINQ 不会避免循环,它只是将它们隐藏起来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多