对象字段不保留值

时间:2014-12-09 20:06:45

标签: c# .net object

在下面的代码中,我有对象Player的实例,其中包含name,numofmentions,s和salience作为其字段。在第二个for循环中,我为每个玩家对象设置val.s的值。然后我将它们加在一起形成一个总和,这很好。但是在下一个(第三个)for循环中,我想使用每个对象的val.s值,但它返回全零。有人可以告诉我为什么吗?我提前感谢您的帮助

for (int i=0;i<players.Count;i++) 
{
    myList.Add(new Player {name = players[i], numMention=playersNumMentions[i]});
}

var mySummedList = myList.GroupBy(x => x.name).Select(x => new Player { name = x.Key, numMention = x.Sum(y => y.numMention)});

foreach (var val in mySummedList)
{
    if (val.numMention > 50000) //differs for different problems
    {
        sql = "SELECT COUNT(Actor1Code) AS S FROM [gdelt-bq:full.events] WHERE Year>=" + predictionDate + " AND (Actor1Code ='" + val.name + "' AND ((Actor2CountryCode = '" + mainPlayer1 + "') OR (Actor2CountryCode='" + mainPlayer2 + "')))";
        response = new WebClient().DownloadString(url + "?q=" + Uri.EscapeUriString(sql));
        value = JsonValue.Parse(response);

        result = value as JsonObject;
        var row = result["modelData"]["rows"][0];
        val.s=((int)row["f"][0]["v"]);

        sumOfS += val.s;                
    }         
}

foreach (var val in mySummedList)
{
    if (val.numMention > 50000) //differs for different problems
    {                             
        val.salience = val.s / sumOfS;

        Console.WriteLine(String.Format("{0}: {1}", val.name, val.salience));
    }
}

3 个答案:

答案 0 :(得分:2)

您正在使用LINQ的Select,它可以懒惰地评估可枚举:

.Select(x => new Player { name = x.Key, numMention = x.Sum(y => y.numMention)});

如果您需要重用Player实例,请在选择后尝试调用ToList:

var mySummedList = myList.GroupBy(x => x.name).Select(x => new Player { name = x.Key, numMention = x.Sum(y => y.numMention)}).ToList();

答案 1 :(得分:1)

我认为这是因为这一行

val.salience = val.s / sumOfS;

因为sumOfS大于val.s并且它是整数除法,所以结果为零。

您可以将val.salience类型更改为double并将行更改为

val.salience = val.s / (double)sumOfS;

答案 2 :(得分:0)

如果Player是一个结构,它将无法工作,如果它是一个类改变foreach而不是

foreach(var x.....)

DO

foreach(Player x....)

并确保val.s的值与0

不同