【发布时间】:2014-03-10 16:41:00
【问题描述】:
在我的 C# 代码中,我有一个列表 List<Tuple<int,string>>。我想选择/将其转换为List<Type>。我想避免迭代我的元组列表并插入其他列表。有没有办法做到这一点?也许使用 LINQ?
【问题讨论】:
-
LINQ 也会迭代,只是没有显示在您的代码中。
标签: c# linq type-conversion tuples
在我的 C# 代码中,我有一个列表 List<Tuple<int,string>>。我想选择/将其转换为List<Type>。我想避免迭代我的元组列表并插入其他列表。有没有办法做到这一点?也许使用 LINQ?
【问题讨论】:
标签: c# linq type-conversion tuples
您不能更改列表的类型。您只能创建另一种类型的新列表并用列表中的转换值填充它。我建议使用正是为此目的而存在的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 });
【讨论】:
您没有显示此类型,但我假设它包含 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<Type> 实际上是List<CustomType>(我称之为MyType)。
我想避免迭代我的元组列表并插入到其他列表中。
LINQ 不会避免循环,它只是将它们隐藏起来。
【讨论】: