1.定义变量
List
List
List
List
2.输入
static void PrintList(IEnumerable
{
foreach (var s in str)
Console.WriteLine(s);
Console.WriteLine("-------------");
}
3.常用操作(命名空间:System.Linq)
Enumberable.Intersect();
// Compare two List
lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase);
PrintList(lstNew);
输出相同元素:JANUARY MARCH
- Enumerable.Except
// Compare two List
and display items of lstOne not in lstTwo lstNew = lstOne.Except(lstTwo, StringComparer.OrdinalIgnoreCase);
PrintList(lstNew);
- Enumerable.Distinct
// Unique List
lstNew = lstFour.Distinct(StringComparer.OrdinalIgnoreCase);
PrintList(lstNew)
- List.ConvertAll
// Convert elements of List
to Upper Case lstNew = lstOne.ConvertAll(x => x.ToUpper());
PrintList(lstNew);
- Enumerable.Concat
// Concatenate and Sort two List
lstNew = lstOne.Concat(lstTwo).OrderBy(s => s);
PrintList(lstNew);
- Enumerable.Concat and Enumerable.Distinct
// Concatenate Unique Elements of two List
lstNew = lstOne.Concat(lstTwo).Distinct();
PrintList(lstNew);
- List.Reverse
// Reverse a List
lstOne.Reverse();
PrintList(lstOne);
- List.RemoveAll
// Search a List
and Remove the Search Item // from the List
int cnt = lstFour.RemoveAll(x => x.Contains("Feb"));
Console.WriteLine("{0} items removed", cnt);
PrintList(lstFour);
- Enumerable.OrderBy and Enumerable.ThenByDescending
// Order by Length then by words (descending)
lstNew = lstThree.OrderBy(x => x.Length)
.ThenByDescending(x => x);
PrintList(lstNew);
- Use the Enumerable.Aggregate method
C#
// Create a string by combining all words of a List
// Use StringBuilder if you want performance
string delim = ",";
var str = lstOne.Aggregate((x, y) => x + delim + y);
Console.WriteLine(str);
Console.WriteLine("-------------");
- Split the string and use the Enumerable.ToList method
C#
// Create a List
from a Delimited string string s = "January February March";
char separator = ' ';
lstNew = s.Split(separator).ToList();
PrintList(lstNew);
Use the List(T).ConvertAll method
C#
// Convert a List
to List List
lstNum = new List (new int[] { 3, 6, 7, 9 }); lstNew = lstNum.ConvertAll
(delegate(int i) {
return i.ToString();
});
PrintList(lstNew);
- Use Enumerable.GroupBy, Enumerable.Select and Enumerable.OrderByDescending
// Count Repeated Words
var q = lstFour.GroupBy(x => x)
.Select(g => new { Value = g.Key, Count = g.Count() })
.OrderByDescending(x => x.Count);
foreach (var x in q)
{
Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}