lonelydev101
lonelydev101

Reputation: 1901

How to compare two lists based on indexes

I have two lists which are identical in length. If one list has 4 elements, other list has also 4 elements. List<string> multipleJMBGs and List<BundleSchedule> schedules

I need to create a check method, which will be checking following:

"1111", "1111" (indexes [23],[41])
"12345", "12345" (indexes [3],[11])
"16872982342716", "16872982342716" (indexes [29],[33])

those are 3 pairs, so we need to groupBy, and extract their indexes (those numbers are just for example purposes):

private bool CheckIfSameUsersHaveSameServices(List<string> multipleJMBGs, List<BundleSchedule> schedules)
{
    var duplicateJMBGs = multipleJMBGs.GroupBy(x => x)
                .Where(group => group.Count() > 1)
                .Select(group => new { jmbg = group.Key }).ToList();


           
    Dictionary<string, string> indexes = new Dictionary<string, string>();

    //fill in dictionary with indexes
    //23,41
    //3,11
    //29,33

    foreach (var pair in indexes)
    {
        var firstToCompare = schedules.ElementAt(Convert.ToInt32(pair.Key));
        var secondToCompare = schedules.ElementAt(Convert.ToInt32(pair.Value));

        //if only one compared pair has same serviceId, return true
        if (firstToCompare.ServiceTypeComplexityId == secondToCompare.ServiceTypeComplexityId)
        {
            return true;
        }
    }
}

Mine question is how to put in Select of GroupBy query also those indexes from a list?

Upvotes: 0

Views: 1108

Answers (2)

jegtugado
jegtugado

Reputation: 5141

You can get the index and value for each enumerable and perform a Join. Fiddle: https://dotnetfiddle.net/0oDJMM

public static void Main()
{
    List<string> foo = new List<string>() {
        "1", "12", "123", "1234", "12345"
    };
    List<string> bar = new List<string>() {
        "123", "a", "b", "1", "12"
    };
    var foos = foo.Select((f, i) => new { idx = i, val = f });
    var bars = bar.Select((b, i) => new { idx = i, val = b });
    var indexes = foos.Join(bars, 
        f => f.val, 
        b => b.val, 
        (f, b) => new { idxA = f.idx, idxB = b.idx });
    
    foreach (var idxs in indexes) {
        Console.WriteLine("idxA: {0} idxB: {1}", idxs.idxA, idxs.idxB); // You can now access the indexes for the matching values
    }
}

Upvotes: 1

Richard Deeming
Richard Deeming

Reputation: 31208

How about:

Dictionary<string, int> jmbgIds = new Dictionary<string, int>(StringComparer.Ordinal);

for (int index = 0; index < multipleJMBGs.Count; index++)
{
    string jmbg = multipleJMBGs[index];
    int id = schedules[index].ServiceTypeComplexityId;
    if (jmbgIds.TryGetValue(jmbg, out var previousId))
    {
        if (previousId != id)
        {
            return false;
        }
    }
    else
    {
        jmbgIds.Add(jmbg, id);
    }
}

return true;

Upvotes: 1

Related Questions