在Linq中

时间:2017-08-19 15:02:28

标签: c# linq

您好我在下面的代码中写了一些人。在查询中,我希望得到所有人,并选择每个人的实例形式,以下代码用于主要方法:

Persons[] person = { new Persons(534, "Komeil", "Shahmoradi", 20, 1.65f, 68.3f), 
                           new Persons(1047, "Ahmad", "Darvishi", 18, 1.72f, 70) ,
                            new Persons(56, "Javad", "Amini", 28, 1.56f, 73.2f),
                            new Persons(2, "Hossein", "Kiany", 17, 1.80f, 65.6f) ,
                           new Persons(192, "Hossein", "Kazemy", 15, 1.80f, 83.6f),
                           new Persons(2002, "Hossein", "Saeedi", 43, 1.80f, 93.6f)};

Random rnd = new Random();
var QpersonsLocation = from value in person
                  select new Duty(rnd.Next(1,2000), value.pName, value.pFamily, value.pAge);


Console.WriteLine("[/] System seting location");
foreach (var item in QpersonsLocation)
{
   Console.WriteLine(item.dId +"\t" + item.dName + "\t" + item.dFamily + "\t" + item.dAge + "\t" + item.dDuttyLocation+"\t");
}

这是我的人类课程:

class Persons
{
    public long pId { get; set; }
    public string pName { get; set; }
    public string pFamily { get; set; }
    public byte pAge { get; set; }
    public float pSize { get; set; }
    public float pWeight { get; set; }

    public Persons(long pId, string pName, string pFamily, byte pAge, float pSize, float pWeight)
    {
        this.pId = pId;
        this.pName = pName;
        this.pFamily = pFamily;
        this.pAge = pAge;
        this.pSize = pSize;
        this.pWeight = pWeight;
    }
}
Duty class的lass代码中的

问题

class Duty
{

    string[] locations = {"Esfahan",
        "Tehran",
        "Mashhad",
        "Shiraz",
        "Hamedan",
        "Azarbayejan"};
    public long dId {get;set;}
    public string dName { get; set; }
    public string dFamily { get; set; }
    public byte dAge { get; set; }

    public string dDuttyLocation { get; set; }

    public Duty(long dId, string dName, string dFamily, byte dAge)
    {
        this.dId = dId;
        this.dName = dName;
        this.dFamily = dFamily;
        this.dAge = dAge;
        Random rnd = new Random();
        int num = rnd.Next(0,locations.Length);
        dDuttyLocation = locations[num];//problem            
    }


}

代码工作正常但位置未保存且dDuttyLocation始终等于最后一个随机数,下图显示了结果: result of program

1 个答案:

答案 0 :(得分:0)

问题是在3021构造函数中创建3021类的新实例的时间太近了。 See here for more info.

类似于你已经为每个人生成一个新Random的方法,你需要生成随机数并将其传递给构造函数,这样它们就不一样了。

为此,您首先需要将您的位置数组设为公共和静态。然后,您可以将LINQ表达式更改为:

Duty