-1

I'm having a tough time with a unique situation. We need to return a unique dataset with all three columns so the result has a unique Company and Item but any of the keys.

We are using LINQ and I have a dataset with the following columns.

Company     Item    Key
------------------------------------------------------------
CompanyA    ItemA   9f94413b-63cb-4ad5-869a-4502988a22c9
CompanyA    ItemA   6c6a1b37-84a5-4878-a493-5dad5bf60ee4
CompanyB    ItemA   25c5ffca-69a5-45a6-9643-635791dc1bfd

The result I'm hoping for looks like this without care as to which key I get.

Company     Item    Key
CompanyA    ItemA   9f94413b-63cb-4ad5-869a-4502988a22c9
CompanyB    ItemA   25c5ffca-69a5-45a6-9643-635791dc1bfd

I've tried every combination of LINQ examples that I could find without success. Is this a case where I first need to get a distinct list of Company/Item then loop again to get a Top(1) for the key on each of the results?

Scott D
  • 35
  • 4

1 Answers1

0

If you have something like this:

public class MyRecord
{
    public string Company {get;set;}
    public string Item {get;set;}
    public string Key {get;set;}
}

Then you can query it using .GroupBy by grouping on Company and Item. Next you can use .Select to build a new MyRecord with the grouped Company and Item values and the first Key from the group:

List<MyRecord> records = new List<MyRecord>()
{
    new MyRecord() { Company = "CompanyA", Item = "ItemA", Key = "9f94413b-63cb-4ad5-869a-4502988a22c9" },
    new MyRecord() { Company = "CompanyA", Item = "ItemA", Key = "6c6a1b37-84a5-4878-a493-5dad5bf60ee4" },
    new MyRecord() { Company = "CompanyB", Item = "ItemA", Key = "25c5ffca-69a5-45a6-9643-635791dc1bfd" }
};

List<MyRecord> results = records
    .GroupBy(r => new { r.Company, r.Item })
    .Select(g => new MyRecord() { Company = g.Key.Company, Item = g.Key.Item, Key = g.First().Key })
    .ToList();

Try it online

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • Thank you for answering my post and actually reading it. Someone marked the post as a duplicate associated with another post which was not the same question/solution. Your answer is very helpful! – Scott D Nov 26 '21 at 22:28