×
Namespaces

Variants
Actions
(Difference between revisions)

Windows Phone 通过Orderby与Count熟悉lamda

From Nokia Developer Wiki
Jump to: navigation, search
hamishwillee (Talk | contribs)
m (Hamishwillee - Format text)
Aady (Talk | contribs)
(Aady -)
Line 1: Line 1:
[[Category:Windows Phone 8]][[Category:Windows Phone 7.5]][[Category:Lang-Chinese]][[Category:General Programming]]
+
[[Category:Windows Phone 8]][[Category:Windows Phone 7.5]][[Category:Lang-Chinese]][[Category:General Programming]][[Category:Windows Phone]]
 
{{ArticleMetaData <!-- v1.2 -->
 
{{ArticleMetaData <!-- v1.2 -->
 
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
 
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->

Revision as of 22:22, 15 February 2013

WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
SignpostIcon Code 52.png
Article Metadata
CompatibilityArticle
Created: Vincent-DEVDIV (30 Jan 2013)
Last edited: Aady (15 Feb 2013)

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

问题是ObservableCollection的OrderBy和Count很难理解:

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");

解答:

  1. lambda表达式的格式一般是
    (input parameters) => expression
    他们构成了类似一个函数,括号里面的是参数,如果参数只有一个那么括号可以省略,=》符号右侧是expression,要执行的代码,expression的结果就是返回值
  2. 比如item => item,那么参数是item,表达式和返回值都是item
    通过VS的Goto Definition看OrderBy的定义,它要求第一个参数是IEnumerable,第二个参数是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
    )

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

122 page views in the last 30 days.