2

I have 2 List objects.

private static List<Logs> _logsDutyStatusChange = new List<Logs>();
private static List<Logs> _logsNonDutyStatusChange = new List<Logs>();

Both of these lists contain a driverid and a date.

I need to see which driverid's are in _logsNonDutyStatusChange that are also in _logsDutyStatusChange.

If they are in _logsNonDutyStatusChange, then replace the date in _logsDutyStatusChange with the MaxDate in _logsNonDutyStatusChange.

How would I go about this. Right now I have the following(does not work):

 foreach (Logs log in _logsDutyStatusChange)
            {
                if (_logsNonDutyStatusChange.Contains(log.did))
                {

                }

            }
2
  • What is your approach? share what you've already done? and where exactly you need help? Commented Apr 18, 2011 at 16:01
  • I have populated the list objects through web service calls using linq. I need help with comparing the data between the 2 objects then populating the _logsDutyStatusChange with the other objects data if the driver id exists. Commented Apr 18, 2011 at 16:04

5 Answers 5

4

If you can use Linq:

var lookup = _logsNonDutyStatusChange.ToLookup(l => l.did);

foreach (Logs log in _logsDutyStatusChange)
{
    if (lookup.Contains(log.did))
    {
        var maxDate = lookup[log.did].Max(l => l.date);
        log.date = maxDate;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

You could implement IEquatable<T>

Comments

1

Try this if you want to do it purely the Linq way

  _logsDutyStatusChange.Where(x=> _logsNonDutyStatusChange.Any(y=>y.DriveId == x.DriveId))
            .ToList().ForEach(xx => xx.Date = _logsNonDutyStatusChange.Where(yy=>yy.DriveId==xx.DriveId)
            .Max(yyy=>yyy.Date));

Comments

0

You can try

 foreach (Logs log in _logsDutyStatusChange)
 {


    if (_logsNonDutyStatusChange.Select (l => l.did).Contains(log.did))
    {

    }

 }

Comments

0

If you must use for-loops, you need this:

foreach (Logs log in _logsDutyStatusChange)
{
    foreach (var nonDutyLog in _logsNonDutyStatusChange)
    {
        if (nonDutyLog.did.Equals(log.did))
        {
            // do something
        }
    }
}

But note that this is O(n*m), which is expensive, particularly if you have a lot of entries. If you need something like this, you'll be better of converting some of these lookups into hash tables. The quick and easy way to do this is with ToLookup():

var nonDutyLookup = _logsNonDutyStatusChange.ToLookup(log => log.did, log => log);

foreach (Logs log in _logsDutyStatusChange)
{
    foreach (matchingLog in nonDutyLookup[log.did])
    {
        // handle the matching log
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.