2017-05-25 47 views
-3

我有一個FUNC看起來像下面遍歷IEnumerable的使用lambda

Func<Product, bool> ItemProduct(Iitem item) => (pro)=> pro.ItemID == item.Id; 

我找這需要多個項目FUNC。我想在下面,但這是不正確的...你能幫我怎麼做到這一點?

Func<Product, bool> ItemProduct(IEnumerable<Iitem> items) => (pro) => pro.ItemID == items.Id; 
+6

什麼是'ItemProduct(IEnumerable的項目)'應該做/返回? –

+2

事實上 - 提供一個[mcve]可以真正澄清這一點,在提出它的時候,你可能會回答你自己的問題。 –

+0

@YacoubMassad它應該返回IEnumerable reddy

回答

1

從評論,它可能是你真正想要生成將自己的Iitem枚舉,並採取Product作爲參數,並返回其所有Iitem(胡)的Id的功能相匹配的ItemIDProduct。這是這樣的:

Func<Product, IEnumerable<Iitem>> ItemProduct(IEnumerable<Iitem> items) => 
    pro => items.Where(item => pro.ItemID == item.Id); 

使用像這樣:

var someItems = new [] { new Iitem { Id = 1 }, new Iitem { Id = 2 } }; 

var f = ItemProduct(someItems); 

var prod = new Product { ItemID = 1; } 

// Results will be an enumeration that will enumerate a single Iitem, the 
// one whose Id is 1. 
var results = f(prod); 

我會離開這裏我原來的猜測,因爲我真不知道你真正想要的。

此方法將返回一個FUNC返回true,如果所有 IDS在items匹配Product傳過來的參數ItemID

Func<Product, bool> ItemProduct(IEnumerable<Iitem> items) => 
    (pro) => items.All(item => pro.ItemID == item.Id); 

像這樣:

var product = new Product() { ItemID = 1 }; 
var itemColl1 = new Iitem[] { new Iitem { Id = 1 }, new Iitem { Id = 2 } }; 
var itemColl2 = new Iitem[] { new Iitem { Id = 1 }, new Iitem { Id = 1 } }; 

var f1 = ItemProduct(itemColl1); 
var f2 = ItemProduct(itemColl2); 

bool thisWillBeFalse = f1(product); 
bool thisWillBeTrue = f2(product); 

如果如果至少有一個Ids匹配,但希望該函數返回true,但不一定全部匹配,則會這樣做。唯一的區別是,items.All()變化items.Any()

Func<Product, bool> ItemProductAny(IEnumerable<Iitem> items) => 
    (pro) => items.Any(item => pro.ItemID == item.Id); 

像這樣:

var f3 = ItemProductAny(itemColl1); 
var f4 = ItemProductAny(itemColl2); 

bool thisWillAlsoBeTrue = f3(product); 
bool thisWillAlsoBeTrueAgain = f4(product); 


var itemColl3 = new Iitem[] { new Iitem { Id = 2 }, new Iitem { Id = 3 } }; 

var f5 = ItemProductAny(itemColl3); 

bool butThisWillBeFalse = f5(product); 
+0

謝謝你解決了我的問題 – reddy

+0

@reddy很棒。在這種情況下,你應該接受它作爲正確答案。 –

1

假設你需要返回這對於一個給定的產品返回true如果從一個給定的所有項具有的功能同樣Id作爲產品的ItemID,你可以使用的items.All(...),而不是單一的ID進行比較:

Func<Product, bool> ItemProduct1(IEnumerable<Iitem> items) 
    => (pro) => items.All(i => pro.ItemID == i.Id); 

如果您需要true的產品,ItemID比賽剛剛Id某些給定的項目,請使用items.Any(...)代替:

Func<Product, bool> ItemProduct1(IEnumerable<Iitem> items) 
    => (pro) => items.Any(i => pro.ItemID == i.Id); 
+0

謝謝你解決了我的問題 – reddy