×
Namespaces

Variants
Actions
(Difference between revisions)

Windows Phone 通过Orderby与Count熟悉lamda

From Nokia Developer Wiki
Jump to: navigation, search
Vincent-DEVDIV (Talk | contribs)
m (Vincent-DEVDIV -)
Vincent-DEVDIV (Talk | contribs)
(Vincent-DEVDIV -)
Line 4: Line 4:
 
问题是ObservableCollection的OrderBy和Count很难理解:
 
问题是ObservableCollection的OrderBy和Count很难理解:
 
[代码]c#/cpp/oc代码:
 
[代码]c#/cpp/oc代码:
 
+
[code]
 
ObservableCollection<string> oc = new ObservableCollection<string>();
 
ObservableCollection<string> oc = new ObservableCollection<string>();
 
oc.Add("abc");
 
oc.Add("abc");
Line 12: Line 12:
 
var oc2 = oc.OrderBy(item => item);
 
var oc2 = oc.OrderBy(item => item);
 
int count = oc.Count(item => item == "beijing");
 
int count = oc.Count(item => item == "beijing");
 
+
[/code]
  
 
解答:
 
解答:

Revision as of 09:32, 30 January 2013

有人问题这个问题,这里总结一下,以便新人查询

问题是ObservableCollection的OrderBy和Count很难理解: [代码]c#/cpp/oc代码: [code] ObservableCollection<string> oc = new ObservableCollection<string>(); oc.Add("abc"); oc.Add("dec"); oc.Add("zhongguo"); oc.Add("beijing"); var oc2 = oc.OrderBy(item => item); int count = oc.Count(item => item == "beijing"); [/code]

解答:

1. lambda表达式的格式一般是 (input parameters) => expression 他们构成了类似一个函数,expression那里就是返回值

2. 比如item => item,那么参数是item,表达式和返回值都是item 再看OrderBy的定义,它要求参数是Func<TSource, TKey> keySelector 也就是说它希望的参数是一个func,这个func的返回值是排序的key, 而你的func是item=>item,它的返回值是item,所以key就是item。

3. 在来看item=>item=="beijing",它的参数是item,表达式是item=="beijing",返回值是bool(true/false) 再看Count的定义,它要求参数为Func<TSource, bool> predicate 也就是说它希望参数是一个func,这个func的返回值是bool,是一个Predicate。 就是说 public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate); 这个函数,枚举source中每一个item,然后调用func检查item是否符合条件,如果符合条件就计数加1.

4. 另外需要只出的是Func定义为: public delegate TResult Func<in T, out TResult>(

       T arg

) 也就是说模板中第一个是参数,第二个是返回值。

192 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×