我有以下代码,它将随机分配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);
}
}
}
}
}
}
答案 0 :(得分:2)
您可以使用Intersect()
查找两个收藏品共有的项目,然后应用Count()
查看交叉点是否至少包含三个项目:
var winners = players.
Where(player => player.Numbers.Intersect(lotto).Count() >= 3);
关于您的实施的几点说明:
Dictionary
并将值设置为1
,而是使用HashSet
:您对密钥感兴趣,而不是值,因此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};
}
}
}
答案 1 :(得分:0)
你可以做条件(使用System.Linq添加):
UsersNumbers.Intersect(GeneratedNumbers).Count() >= 3