Coderwars 6 kyu : Meeting

题目

John has invited some friends. His list is:

s =

"Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";

Could you make a program that

  • makes this string uppercase
  • gives it sorted in alphabetical order by last name.

When the last names are the same, sort them by first name. Last name and first name of a guest come in the result between parentheses separated by a comma.

So the result of function meeting(s) will be:

"(CORWILL, ALFRED)(CORWILL, FRED)(CORWILL, RAPHAEL)(CORWILL, WILFRED)(TORNBULL, BARNEY)(TORNBULL, BETTY)(TORNBULL, BJON)"

It can happen that in two distinct families with the same family name two people have the same first name too.

Notes

You can see another examples in the “Sample tests”.

代码

using System.Collections.Generic;
using System.Linq;

public class JohnMeeting
{
    public static string Meeting(string s) {
        string upper=s.ToUpper();
    string[] names=upper.Split(';').ToArray();    
    List<Fullnames> namelist=new List<Fullnames>();

    for(int i=0;i<names.Length;i++){
      string s1=names[i];
      string[] ss=s1.Split(':').ToArray();
      namelist.Add(new Fullnames {firstname=ss[0],lastname=ss[1]} );
    }
    var ordered=namelist.OrderBy(c=>c.lastname).ThenBy(c=>c.firstname).Select(fn => fn.ToString());
    return string.Join("",ordered.ToArray());
    }
}

public class Fullnames{
  public string firstname;
  public string lastname;
  public override string ToString(){
    return string.Format("({0}, {1})",lastname,firstname);
  }
}

解题思路

本题需要用到排序,可以直接用OrderBy()的方法来进行。
而要实现排序,就需要先得到装有名字的列表,可以新建一个类,然后列表中的每一项元素都是该类的一个实例。

发表评论

您的电子邮箱地址不会被公开。