Skip to content

Instantly share code, notes, and snippets.

@kkdai
Created February 14, 2014 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkdai/8987515 to your computer and use it in GitHub Desktop.
Save kkdai/8987515 to your computer and use it in GitHub Desktop.
Some sample about lambda
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
List<string> myStringLists = new List<string>();
myStringLists.Add("1145");
myStringLists.Add("22");
myStringLists.Add("1");
myStringLists.Add("55");
myStringLists.Add("519");
List<int> retList = new List<int>();
retList = GetSquaresOfPositiveByLambda(myStringLists);
/////
string[] days = { "ass", "asdasd", "bbsd", "ass", "www", "bbs", "ee", "sss", "wwss"};
Dictionary<char, List<string>> s1 = GetIndex(days);
Dictionary<char, List<string>> s2 = GetIndexByLambda(days);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static List<int> GetSquaresOfPositiveByLambda(List<string> strList)
{
return strList
.Select(s => Int32.Parse(s)) // 转成整数
.Where(i => i % 2 == 0) // 找出所有偶数
.Select(i => i * i) // 算出每个数的平方
.OrderBy(i => i) // 按照元素自身排序
.ToList(); // 构造一个List
}
static Dictionary<char, List<string>> GetIndexByLambda(IEnumerable<string> keywords)
{
return keywords
.GroupBy(k => k[0])
.ToDictionary(
g => g.Key,
g => g.OrderBy(k => k).ToList());
}
static Dictionary<char, List<string>> GetIndex(IEnumerable<string> keywords)
{
// 定义字典
var result = new Dictionary<char, List<string>>();
// 填充字典
foreach (var kw in keywords)
{
var firstChar = kw[0];
List<string> groupKeywords;
if (!result.TryGetValue(firstChar, out groupKeywords))
{
groupKeywords = new List<string>();
result.Add(firstChar, groupKeywords);
}
groupKeywords.Add(kw);
}
// 为每个分组排序
foreach (var groupKeywords in result.Values)
{
groupKeywords.Sort();
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment