簡體   English   中英

Linq的Lambda聲明

[英]Lambda Statements in Linq

是否有可能在Linq中執行以下操作?

List<Group> groupsCollection = new List<Group>();
groups.Select( g => {
    String id = g.Attributes["id"].Value;
    String title = g.Attributes["title"].Value;
    groupsCollection.Add( new Group(id, title) );
} );

這只是一個例子。 我知道Foreach循環就足夠了,但我在詢問它是否可行。

我試過了,它說:

Cannot convert lambda expression to type System.Collections.IEnumerable<CsQuery.IDomObject> because it's not a delegate type

編輯:組是我的自定義類。 組是CsQuery Dom對象的集合。 您可以將它們視為html錨元素的集合。 它們是IEnumerable。

我想你正在尋找這個:

groupsCollection = groups.Select(g =>
    new Group(g.Attributes["id"].Value,
              g.Attributes["title"].Value)).ToList();

說明:

Select()將序列的每個元素投影到新表單中。 (來自MSDN

它基本上是一個轉換函數,它接受一個I​​Enumerable並以任何你喜歡的方式將它轉換為另一個IEnumerable,這似乎正是你想要的。

Select()接受一個返回值的lambda表達式; 它不應該有任何生效。

你要

var groupsCollection = groups.Select(g => {
    return ...;
}).ToList();

您可以使用構造函數使用查詢對其進行初始化:

var query = groups.Select( g => {
    String id = g.Attributes["id"].Value;
    String title = g.Attributes["title"].Value;
    return new Group(id, title);
});
List<Group> groupsCollection = new List<Group>(query);

不要修改linq查詢中的colections,而是選擇可用於修改集合的數據。

正如你所說,你知道使用ForEach是相關的。 但是,如果你能以另一種方式做到這一點,你只是好奇 正如其他人指出的那樣,您可以使用Select{...}的代碼應該返回一些值。 但是,您可以這樣做,如果您想使用TakeWhile根據某些條件stopbreak循環,這樣做會更好:

groups.TakeWhile( g => {
       String id = g.Attributes["id"].Value;
       String title = g.Attributes["title"].Value;
       groupsCollection.Add( new Group(id, title) );
       return true;//If you want to break the loop, just return false accordingly.
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM