3
var top100 = (from m in _messages
              where m.IsSent == false
              select m).Take(100);

foreach (var message in top100)
{
    message.IsSent = _sms.SendSMS(message.Source, message.Destination, message.TextMessage);
}

var count = _messages.Count(x => x.IsSent);

I cannot understand why the variable count is equal to 0. I would have thought that I was working with references to my message objects, but if count is 0, does that mean I'm working with copies? What am I doing wrong?

4

3 に答える 3

3

I just tried investigating your question and I didn't reproduce it so it makes me wonder if your IsSent is actually false and that's why you get your result.

void Main()
{
    var top100 = (from m in Messages where m.IsSent == false select m).Take(100);   
    foreach (var message in top100) { 
        message.IsSent = true; 
    }
    var count = Messages.Count(x => x.IsSent); 
    Console.WriteLine(count);
}
List<Message> Messages {
    get {
        if(_messagesList == null) {
            _messagesList = new List<Message>();
            for (int i = 0; i < 100; i++)
                _messagesList.Add(new Message { IsSent = false });
        }
        return _messagesList;
    }
}
List<Message> _messagesList;
class Message {
    public bool IsSent { get; set; }
}

Output is 100

于 2012-10-02T00:12:06.303 に答える
1

Just grab the count from top100 after the sms processing.

var count = top100.Count(m => m.IsSent);

Let's pretend a count was returning with your current code. It would return a count that wasn't correct for the 100 messages you had just attempted. So say _messages had 101 messages in it. 100 of them had IsSent set to false, and one had IsSent set to true. After setting IsSent to true on the 100 you get in your first line, _messages.Count(x => x.IsSent) would return 101. Depending on what you are using count for, 101 might not make sense.

于 2012-10-01T23:59:05.800 に答える
0

You're dealing with Enumerable. Take does a yield result, so unless you add a .ToList() at the end, your .Count() call will essentially just re-apply the from m in _messages where m.IsSent == false Returning the next 100 unsent messages.

Add a .ToList() to your initial pull of 100 then the .Count() will evaluate against the initial 100 you processed.

于 2012-10-02T00:11:10.337 に答える