score:1

Accepted answer

Here is the right answer (to be compared with Alex Aza's one : filteredItemsAlexAza and filteredItemsSsithra give different results since the less common data is not also the minimum one anymore - here 2005 instead of 2001 for A01)

class Program
{
    public static void Main(string[] args)
    {
        var items = new List<Item>
        {
            new Item { Code = "A01", Year = "2005" },
            new Item { Code = "A01", Year = "2002" },
            new Item { Code = "B01", Year = "2002" },
            new Item { Code = "C01", Year = "2003" },
        };

        var filteredItemsAlexAza = items.Select(cod => cod.Code).Distinct().Select(cod => items.OrderBy(itm => itm.Year).First(itm => itm.Code == cod)).ToList();
        var filteredItemsSsithra = items
            .Select(item => new { Item = item, NbItemsWithSameYear = items.Where(i => i.Year == item.Year).Count() })
            .GroupBy(ano => ano.Item.Code)
            .Select(group => group.OrderBy(ano => ano.NbItemsWithSameYear).First().Item)
            .ToList();
    }

    public class Item
    {
        public string Code { get; set; }
        public string Year { get; set; }
    }
}

score:0

You can google for "Concordance source code" in your preferred implementation language.

score:2

I'm sorry for making it in C#. Hope you will not have problems to convert it to VB.NET.

var filteredItems = items
    .Select(cod => cod.Code).Distinct()
    .Select(cod => items.OrderBy(itm => itm.Year).First(itm => itm.Code == cod))
    .ToList();

Test code:

public class Item
{
    public string Code { get; set; }

    public string Year { get; set; }
}

public static void Main(string[] args)
{
    var items =
        new List<Item>
        {
            new Item{ Code = "A01", Year = "2001" },
            new Item{ Code = "A01", Year = "2002" },
            new Item{ Code = "B01", Year = "2002" },
            new Item{ Code = "C01", Year = "2003" },
        };

    var filteredItems = items
        .Select(cod => cod.Code).Distinct()
        .Select(cod => items.OrderBy(itm => itm.Year).First(itm => itm.Code == cod))
        .ToList();
}

score:0

Sorry but the proposed solution absolutely doesn't fullfill Pileggi's initial requirements. "The less common value as possible" has become "the min value". Both match in this precise case, which gives the illusion that Alex Aza's answer is right but it is just a coincidence.


Related Articles