Group by wordlist by their first letter in LINQ

I need to group by the first letter of a word in LINQ. Since I'm new to LINQ, I don't know how to debug it.

//Code

var words4 = testDS.Tables["Words4"].AsEnumerable(); var wordGroups = from w in words4 group w by w.Field<string>("word")[0] into g select new {FirstLetter = g.Key, Words = g }; foreach (var g in wordGroups) { Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter); Console.WriteLine(g.Field<string>("word")); } 

Executing this Invalid Arguments function in the last Console.WriteLine.

+4
source share
5 answers

Try adding a loop inside to get more accurate results.

Replace:

 Console.WriteLine(g.Field<string>("word")); 

WITH

 foreach (var w in g.Words) { Console.WriteLine(w.Field<string>("word")); } 
+2
source

Since in your select you created an anonymous object with the field specified as Words , and then you access it through word , the Field extension method is also not required.

You need to replace:

 Console.WriteLine(g.Field<string>("word")); 

with

 Console.WriteLine(g.Words); 
+1
source

Firstly, instead of your group consisting of DataRows, since you want to show only words, I would select the words you want from datarow. Secondly, remember that the words are on the list. If you want to print them, you will need to loop or do something like string.Join (as I do below). For instance:

 var wordGroups = from w in words4.Select(w => w.Field<string>("word")) group w by w[0] into g select new { FirstLetter = g.Key, Words = g }; foreach (var g in wordGroups) { Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter); Console.WriteLine(string.Join(", ", g.Words)); } 
+1
source

This should get what you want in wordGroups using Linq syntax :

Replace:

 Console.WriteLine(g.Field<string>("word")); 

with:

 g.Words.ForEach(w => Console.WriteLine(W.Field<string>("word")); 
+1
source

Another option would be something like this?

 Dictionary<string, List<Product>> groupedDictionary = _db.Products.GroupBy(g => g.Name.Substring(0,1)).ToDictionary(g => g.Key, g => g.ToList()); 
+1
source

Source: https://habr.com/ru/post/1469413/


All Articles