2017-05-25 83 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