首页 > 解决方案 > 用另一个带有条件的列表填充列表

问题描述

我有一个清单:

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 myList3d是随机添加的(不要忘记我不想添加两次“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

我试图这样做,但我有很多条件是不可读的。

任何帮助表示赞赏。

标签: c#

解决方案


有很多方法可以解决它,如果您分享您的方法会更好,我们可以帮助您。无论如何,以下是您可以选择的一种方法。

您可以编写一个名为 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);

推荐阅读