Group several values into one sequence using C# [closed]
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this questionI have the following list :
UserName LanguageSpoken
-------------------------
Bob English
Bob French
Alan Italian
Alan Spanis开发者_运维技巧h
Alan German
I'd like to have another list like :
Bob English/French
Alan Italian/Spanish/German
How can I do that using lambda expressions in C#.
Thanks
My approach would be to use a regex to parse the data and then linq to group it. Can you show us what you have tried so far?
Below is an implementation that you can play around with.
class UserLanguage
{
public string UserName { get; set; }
public string Language { get; set; }
}
static class EnumerableExtensions
{
public static string Concatenate(this IEnumerable<string> source, string delimiter)
{
using (var enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
StringBuilder builder = new StringBuilder(enumerator.Current);
while (enumerator.MoveNext())
{
builder.Append(delimiter).Append(enumerator.Current);
}
return builder.ToString();
}
else
{
return null;
}
}
}
}
class Program
{
static void Main(string[] args)
{
// assuming that you already have data stored in a structure similar to this
var rawData = new List<UserLanguage>()
{
new UserLanguage { UserName = "Bob", Language = "English" },
new UserLanguage { UserName = "Bob", Language = "French" },
new UserLanguage { UserName = "Alan", Language = "Italian" },
new UserLanguage { UserName = "Alan", Language = "Spanish" },
new UserLanguage { UserName = "Alan", Language = "German" },
};
// group these objects together by UserName
var groupedData = rawData.GroupBy(userLanguage => userLanguage.UserName);
foreach (var grouping in groupedData)
{
Console.WriteLine(grouping.Key + "\t" + grouping.Select(userLanguage => userLanguage.Language).Concatenate("/"));
}
}
}
class Person
{
string UserName {get; set;}
string LanguageSpoken {get; set;}
}
var table = new List<Person>() {
new Person() {
UserName = "Bob";
LanguageSpoken = "English"
}
/* next persons*/
};
var userNameGroups = from n in table
group n by n.UserName into g
select new {
keyUserName = g.Key,
LanguageSpoken = g
};
foreach(var g in userNameGroups) {
Console.Write(g.keyUserName.ToString());
foreach(var n in g.LanguageSpoken) {
Console.WriteLine(n.ToString());
}
}
If your List is something like:
class Person
{
public string Name { get; set; }
public string Language { get; set; }
}
List<Person> myList = /* Initialization */
Then LINQ GroupBy should do the trick:
myList.GroupBy(a => a.Name);
Hope this helps.
精彩评论