问题描述
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> items,int count)
{
int i = 0;
foreach (var item in items)
{
if (count == 1)
yield return new T[] { item };
else
{
foreach (var result in GetPermutations(items.Skip(i + 1),count - 1))
yield return new T[] { item }.Concat(result);
}
++i;
}
}
public static List<List<int>> GetAllValidCombinations(List<int> items)
{
var finalList = new List<List<int>>();
switch (items.Count)
{
case 1:
finalList.Add(items);
break;
case 3:
finalList.AddRange(GetPermutations(items,2));
finalList.AddRange((List<List<int>>)GetPermutations(items,3));
break;
}
return finalList;
}
,我想从 GetAllValidCombinations 获取列表。
在第一行中 GetAllValidCombinations 的情况3:
错误CS1503参数1:无法从'System.Collections.Generic.IEnumerable
并且如果我尝试第二行即时通讯遇到错误,则指定的转换无效
我如何在一行中进行投射?
解决方法
/// `videosArray` holds the videos that will be cycled through.
private static let videosArray = ["v708953783","v70878990"]
/// `nextStreamIndex` holds the index of the video that should be cycled to next.
private var nextVideoIndex = 0
@IBAction func nextButtonPress(_ sender: Any) {
let videoToPlay = TwitchVideoPlayerViewController.videosArray[nextVideoIndex]
nextVideoIndex = (nextVideoIndex + 1) % TwitchVideoPlayerViewController.videosArray.count
twitchPlayer.setVideo(to: videoToPlay,timestamp: 0)
}
期望AddRange
个IEnumerable
,但是您给了List
个IEnumerable
个。那些IEnumerable
可以是任何东西,不一定是列表,对吧?它们可能是我编写的集,数组或其他某种类型,恰好实现IEnumerable
...这就是编译器给您错误的原因。
正如您所写的IEnumerable<T>
,我们可以看到它们实际上是GetPermutations
的数组!因此,您正在尝试向列表列表中添加一堆数组!那没有多大意义,是吗?
幸运的是,T
将任何ToList
转换为IEnumerable
。您应该使用List
将此方法应用于嵌套在外部IEnumerable
中的每个IEnumerable
:
Select
,
清除程序的答案是金钱,也可以通过仅使用内部集合中的列表并将其完全通用来对其进行一些重构。
public static IEnumerable<List<T>> GetPermutations<T>(List<T> items,int count)
{
for (var index = 0; index < items.Count; index++)
if (count == 1)
yield return new List<T> { items[index] };
else
foreach (var result in GetPermutations(items.Skip(index + 1).ToList(),count - 1))
yield return new List<T> { items[index] }
.Concat(result)
.ToList();
}
public static IEnumerable<List<T>> GetAllValidCombinations<T>(List<T> items)
{
if (items.Count == 1)
return new List<List<T>> {items};
if (items.Count == 3)
return GetPermutations(items,2)
.Concat(GetPermutations(items,3));
return Enumerable.Empty<List<T>>();
}
用法
var results = GetAllValidCombinations(new List<int>() {1,2,3});
foreach (var result in results)
Console.WriteLine(string.Join(",",result));
输出
1,2
1,3
2,3
1,3