[英]comparing values using C# and inserting row IF true
我有以下代碼,將隨機分配6個數字到我的數組。
public void LottoWinners(object sender, EventArgs e)
{
Dictionary<int, int> number = new Dictionary<int, int>();
Random generator = new Random();
while (number.Count < 6)
{
number[generator.Next(1, 49)] = 1;
}
string[] lotto = number.Keys.OrderBy(n => n).Select(s => s.ToString()).ToArray();
//write some logic to find out who has 3 match numbers
//and assign there ticket to the winners table tblWinners
}
然后我需要將數組中的值與tblTickets表中的值進行比較,以查看獲勝者是誰。 但是,我需要打敗獲勝者:
因此,如果它們有3個匹配的數字,那么將ticketID插入到tblWinners表中。
我正在考慮寫一個案例陳述但是如何檢查是否平等?
問題是我在表中保存我的值,如下所示:
tblLotto(val0,val1,val2,val3,val4,val5)
所以我需要使用某種邏輯來搜索我的表格....
我的球員類看起來像這樣:
公共類玩家{public void LottoDraw(object sender,EventArgs e){var connectionstring =“Server = C; Database = lotto; User Id = lottoadmin; Password = password;”;
using (var con = new SqlConnection(connectionstring)) // Create connection with automatic disposal
{
con.Open();
// Create new DataTable
DataTable player = new DataTable();
{
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter("SELECT TOP 1 LOTTOID, VAL0, VAL1, VAL2, VAL3, VAL4, VAL5 FROM tblLotto ORDER BY NEWID()", con))
{
// Use DataAdapter to fill DataTable
a.Fill(player);
}
}
}
}
}
}
您可以使用Intersect()
查找兩個集合共有的項目,然后應用Count()
來查看交集是否至少有三個項目:
var winners = players.
Where(player => player.Numbers.Intersect(lotto).Count() >= 3);
關於您的實施的幾點說明:
HashSet
而不是使用Dictionary
並將值設置為1
:您對鍵而不是值感興趣,因此Set
更合適 var lotto = new HashSet<int>(...); // put six numbers here
var winners = players.
Where(player => player.Numbers.Where(n => lotto.Contains(n)).Count() >= 3);
編輯:(響應問題的編輯)您的Player
類包含玩家的數字作為單獨的屬性。 您可以通過添加屬性Numbers
來添加將其作為集合檢索的方法,如下所示:
class Player {
...
public int val0, val1, val2, val3, val4, val5, val6;
public IEnumerable<int> Numbers {
get {
return new[] {val0, val1, val2, val3, val4, val5, val6};
}
}
}
你可以做條件(使用System.Linq添加):
UsersNumbers.Intersect(GeneratedNumbers).Count() >= 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.