How to use LINQ to select some fields.

john zyd 421 Reputation points
2023-01-04T23:14:38.713+00:00

Hello:
I have this requirements, the following is the data:
var A1 = ("A", "EUR/USD", "EURO");
var A2 = ("A", "CHF/USD", "CHF");
var A3 = ("A", "EUR/GBP", "EURO");
var A4 = ("B", "EUR/USD", "EURO");
var A5 = ("B", "CHF/USD", "CHF");
var A6 = ("B", "EUR/GBP", "EURO");
var A7 = ("C", "EUR/USD", "EURO");
var A8 = ("C", "CHF/USD", "CHF");
List<(string, string, string)> forex_pairs = new()
{
A1, A2, A3, A4, A5, A6, A7, A8
};
I want to select the first item from the list of tuples, where the last 2 items are in the same group.
In the above example, I want to get the following results:
Group#1: ("EUR/USD", "EURO") have the following HashSet<string> members: ("A", "B", "C");
Group#2: ("CHF/USD", "CHF") have the following HashSet<string> members: ("A", "B", "C");
Group#3: ("EUR/GBP", "EURO") have the following HashSet<string> members: ("A", "B");
I know how to group by the last 2 items, but I don’t know how to find the first item and put them into a HashSet. Please advise,
Thanks,

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2023-01-05T00:30:08.487+00:00

    Once you've grouped by the second & third items you'll have an IEnumerable<> of your items per group, so you can just .ToHashSet() them:

       var A1 = ("A", "EUR/USD", "EURO");  
       var A2 = ("A", "CHF/USD", "CHF");  
       var A3 = ("A", "EUR/GBP", "EURO");  
       var A4 = ("B", "EUR/USD", "EURO");  
       var A5 = ("B", "CHF/USD", "CHF");  
       var A6 = ("B", "EUR/GBP", "EURO");  
       var A7 = ("C", "EUR/USD", "EURO");  
       var A8 = ("C", "CHF/USD", "CHF");  
         
       List<(string, string, string)> forex_pairs = new()  
       {  
       	A1, A2, A3, A4, A5, A6, A7, A8  
       };  
         
       var groups = new List<Group>();  
         
       foreach (var group in forex_pairs.GroupBy(p => new { Code = p.Item2, Name = p.Item3 })) {  
       	groups.Add(new Group(  
       		group.Key.Code,  
       		group.Key.Name,  
       		group.Select(g => g.Item1).ToHashSet()  
       	));  
       }  
         
       foreach (var group in groups) {  
       	Console.WriteLine($"{group.Code}+{group.Name}: {string.Join(", ", group.GroupIds)}");  
       }  
         
       record Group(string Code, string Name, HashSet<string> GroupIds);  
    

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-01-05T00:23:47.463+00:00

    just select first of group:

    var list = forex_pairs  
        .GroupBy(r => new { r.Item2, r.Item3 }, r => r)  
        .Select(r => r.First());  
      
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.