如何在 LINQ 和 Rx 之间共享查询逻辑?即,如果我有时需要查询IObservable
流,有时需要查询IEnumerable
,但每个中的逻辑完全相同,有没有办法共享该逻辑?
也许一个例子会有所帮助。在下面的Queries
课程中,我想结合人员和购买的顺序来生成一个“通知”字符串。请注意,我必须复制完全相同的逻辑;唯一不同的是,一个是IEnumerable
,一个是IObservable
。有什么方法可以合并这两个功能吗?我尝试过使用 and 的各种组合ToObservable
,ToEnumerable
但我尝试过的一切似乎要么挂起,要么没有产生任何结果。
(更高级的问题:这正是创建高级类型的想法来解决的问题吗?即,这在 Haskell 或 Scala 中甚至不是问题吗?)
static class Queries {
static IObservable<string> GetPurchaseNotices(IObservable<Person> people, IObservable<Purchase> purchases) {
return from person in people
from purchase in purchases
where person.Id == purchase.PurchaserId
select person.Name + " purchased a " + purchase.ItemName;
}
static IEnumerable<string> GetPurchaseNotices(IEnumerable<Person> people, IEnumerable<Purchase> purchases) {
return from person in people
from purchase in purchases
where person.Id == purchase.PurchaserId
select person.Name + " purchased a " + purchase.ItemName;
}
}
class Person {
public Person(int id, string name) {
Id = id;
Name = name;
}
public string Name;
public int Id;
}
class Purchase {
public Purchase(int purchaserId, string itemName) {
PurchaserId = purchaserId;
ItemName = itemName;
}
public int PurchaserId;
public string ItemName;
}