c# - 用另一个带有条件的列表填充列表
问题描述
我有一个清单:
List<string> letters = {"a", "b", "c", "d", "e", "f"};
我有另一个包含另一个字符串的列表:
List<string> myList1 = { "f3", "g4", "h5" };
List<string> myList2 = { "z5", "w7", "q9" };
List<string> myList3 = { "k5", "n7" };
我想用letters
带有条件的列表填充 myLists:每个列表总共可以包含 5 个元素,并且不要为同一个列表添加两次字母。
在上面的例子中,
myList1 = { "f3", "g4", "h5", "a", "b"};
myList2 = { "z5", "w7", "q9", "c", "d"};
myList3 = { "k5", "n7", "e", "f", "d" };
关于 to myList3
,d
是随机添加的(不要忘记我不想添加两次“e”或“f”)。
请注意,如果我有这种情况:
List<string> myList1 = { "f3", "g4", "h5", "t3", "u6" };
List<string> myList2 = { "z5", "w7", "q9", "k9" };
List<string> myList3 = { "k5", "n7", "d3", "n6" };
输出是:
myList1 = { "f3", "g4", "h5", "t3", "u6" };
myList2 = { "z5", "w7", "q9", "k9", "a" };
myList3 = { "k5", "n7", "d3", "n6", "b" };
如果它有帮助, myList1 的元素比它的声明时多/myList2
相等myList3
。
我试图这样做,但我有很多条件是不可读的。
任何帮助表示赞赏。
解决方案
有很多方法可以解决它,如果您分享您的方法会更好,我们可以帮助您。无论如何,以下是您可以选择的一种方法。
您可以编写一个名为 Fill 的扩展方法。
public static class Extension
{
public static IEnumerable<T> Circle<T>(this IEnumerable<T> list, int startIndex)
{
return list.Skip(startIndex).Concat(list.Take(startIndex));
}
public static void Fill<T>(this List<T> source, List<T> reference, int maxCount,ref int index)
{
if(source.Count() >= maxCount) return;
var difference = source.Count() - maxCount;
var newReferenceList = reference.Circle(index);
source.AddRange(newReferenceList.Where(x=>!source.Contains(x)).Take(maxCount- source.Count()));
index+=Math.Abs(difference);
if(index > maxCount) index = 0;
}
}
然后在你的客户中,
int index = 0;
myList1.Fill(letters,5,ref index);
myList2.Fill(letters,5,ref index);
myList3.Fill(letters,5,ref index);
推荐阅读
- python - ImportError:DLL加载失败:系统无法访问该文件
- android - Twitter 流媒体 API HTTP 420
- python-3.x - 如何将 python windowed() 迭代到最后一个元素?
- excel - 用于自动填充值的 Google 表格宏
- php - 正则表达式 PHP:在查询 db2 中查找丢失的分号
- javascript - 我怎样才能简化这个?(这里是菜鸟)
- kotlin - 有没有办法设置`Observable
` 不使用 `map{ }` - c# - 如何在任务栏中将新的 WPF 窗口显示为新的应用程序/图标(win10 c#wpf)
- html - 为什么坚持页脚方法不适用于 Safari 13.0.5 版本
- sql - 使用 SQL Server 查找列中的空白