C # Linq GroupBy

Given a list of strings like this

"Val.1.ValueA"
"Val.1.ValueB"
"Val.1.ValueC"
"Val.2.ValueA"
"Val.2.ValueB"
"Val.2.ValueC"
"Val.3.ValueA"
" Val.3.ValueB "
" Val.3.ValueC "

How can I write a linq groupby statement to group by the first part of a line, including a number? In other words, in the above case, I need a list of 3 groups Val. 1, Val. 2, Val. 3

+3
source share
2 answers

Use String.Split()to determine your group key:

var groups = myList.GroupBy(x => { var parts = x.Split('.'); 
                                   return parts[0] + parts[1]; });

This will work regardless of the length of both parts of the key (before and after the point).

:

, , , . :

var groups = myList.GroupBy(x => 
    { 
        var parts = x.Split('.'));
        int num = 0;
        return parts[0] + parts.Where(p => p.All(char.IsDigit)
                               .First( p => int.TryParse(p, out num));
    }
);
+5

:

var groups = list.GroupBy(s => s.Substring(0, 5));

:

var groups = list.GroupBy(s => {
     var fields = s.Split('.');
     return String.Format("{0}.{1}", fields[0], fields[1]); 
});
+5

All Articles