user380432
user380432

Reputation: 4779

C# comparing two object values

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))
                {

                }

            }

Upvotes: 2

Views: 420

Answers (5)

Aliostad
Aliostad

Reputation: 81700

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));

Upvotes: 1

JSBձոգչ
JSBձոգչ

Reputation: 41388

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
    }
}

Upvotes: 0

František Žiačik
František Žiačik

Reputation: 7614

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;
    }
}

Upvotes: 4

Bala R
Bala R

Reputation: 109017

You can try

 foreach (Logs log in _logsDutyStatusChange)
 {


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

    }

 }

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 191036

You could implement IEquatable<T>

Upvotes: 3

Related Questions