[英]Inserting data into tables by comparing
我正在使用表格存儲課程one
部分的主題名稱。 我的問題是,如何才能將主題名稱從一個表插入到另一個表中,使得同一時間不能出現兩個主題。
范例:
Table-1
Hour Subject-name
1 C#
2 Java
3 OS
4 C++
5 DBMS
我需要以這種方式向另一個表( table-2
輸入相同的值集:
Table-2
Hour Subject-name
1 OS
2 DBMS
3 C#
4 Java
5 C++
我曾經為列表隨機播放操作,以便隨機播放元素。 但是,有可能兩次發生同一主題。
public static void Shuffle<T>(IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
您需要隨機播放 ,然后檢查是否違反了規則 ,然后重試。
以下是執行此操作的一種方法:
Random rng = new Random();
private IList<Course> SmartShuffle(IList<Course> oldList)
{
IList<Course> newList = new List<Course>();
while (true)
{
var randomOrder = oldList.OrderBy(x => rng.Next()).ToList();
int counter = 0;
foreach(var course in oldList)
{
newList.Add(new Course() { Name = randomOrder[counter].Name, Hour = course.Hour });
counter++;
}
int differenceCount = newList.Count(n => oldList.Any(o => o.Name == n.Name && o.Hour != n.Hour));
// leave only one of the below if statements
// case at least 1 element should be different
if (differenceCount > 0)
break;
// case all elements must be different
if (differenceCount == oldList.Count)
break;
}
return newList;
}
public class Course
{
public string Name { set; get; }
public int Hour { set; get; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.