110,502
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
public class Program
{
public static void Main(string[] args)
{
List<Man> manlist =new List<Man>()
{
new Man{Id="1"},
new Man{Id="2"},
new Man{Id="3"},
new Man{Id="4"},
};
List<Project> projectlist = new List<Project>()
{
new Project{Id="0001"},
new Project{Id="0002"},
new Project{Id="0003"},
new Project{Id="0004"},
new Project{Id="0005"},
new Project{Id="0006"},
};
for (int i = 0; i < projectlist.Count; i++)
{
if (i%manlist.Count == 0)
{
manlist = manlist.OrderBy(x => Guid.NewGuid()).ToList();
}
projectlist[i].ManId = manlist[i%manlist.Count].Id;
}
projectlist.ForEach(p => Console.WriteLine(p.Id + ":" + p.ManId));
Console.Read();
}
}
public class Man
{
public string Id { get; set; }
}
public class Project
{
public string Id { get; set; }
public string ManId { get; set; }
}
}
for (int i = 0; i < 项目list.Count; i++)
{
if (i%人员list.Count == 0)
{
人员list = 人员ist.OrderBy(x => Guid.NewGuid()).ToList();
}
项目list[i].对应人员ID = 人list[i%人list.Count].人员ID;
}
private void btnRun_Click(object sender, EventArgs e)
{
//人名表个数
int iPersonLen = Convert.ToInt32(txtPersonCnt.Text);
//项目表个数
int iProjectLen = Convert.ToInt32(txtProjectCnt.Text);
string[] arrPerson = new string[iPersonLen];
string[] arrProject = new string[iProjectLen];
//添加测试数据
for (int i = 0; i < arrPerson.Length; i++)
{
arrPerson[i] = string.Format("第{0}个人", i);
}
Random ran = new Random(DateTime.Now.Millisecond);
if (iProjectLen > iPersonLen)
{
//确保每个人名都有
Array.Copy(arrPerson, arrProject, iPersonLen);
//之后的人名随机取
for (int i = iPersonLen; i < iProjectLen; i++)
{
//随机取数,数可能会重复
int iRanIndex = ran.Next(0, iPersonLen);
arrProject[i] = arrPerson[iRanIndex];
}
//打乱项目表次序,使得结果看起来无序
arrrandom(ref arrProject);
}
else
{
//方法1:人名无重复
//打乱人名表次序
arrrandom(ref arrPerson);
Array.Copy(arrPerson, arrProject, iProjectLen);
////方法2:人名可重复
//for (int i = 0; i < iProjectLen; i++)
//{
// //随机取数,数可能会重复
// int iRanIndex = ran.Next(0, iProjectLen - iPersonLen);
// arrProject[i] = arrPerson[i];
//}
}
}
/// <summary>
/// 打乱数组次序
/// </summary>
/// <param name="arr"></param>
private void arrrandom(ref string[] arr)
{
Random ran = new Random();
int k = 0;
string strtmp = "";
for (int i = 0; i < arr.Length; i++)
{
k = ran.Next(0, arr.Length);
if (k != i)
{
strtmp = arr[i];
arr[i] = arr[k];
arr[k] = strtmp;
}
}
}