[英]Linq To Objects C#
我想获取债券及其到期日的关联集合,其中maturity.matamount> 200000。
编辑:(我只希望每个债券的到期日集合包括到期日> 200000)
这是一个具有defs类的program.cs以及一种为查询填充测试数据的方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinqToObjects
{
class Program
{
static void Main(string[] args)
{
Program.QueryCollection();
Console.ReadLine();
}
public static void QueryCollection()
{
List<Bond> bonds = Program.BuildCollections();
//how do I get a list of Bonds that have a maturity.MatAmount > 200,000?
}
public static List<Bond> BuildCollections()
{
List<Bond> bonds = new List<Bond>();
Bond bond;
for (int i = 1; i <= 10; i++)
{
bond = new Bond() {ID = i, Title = "Bond Title " + i.ToString() };
for (int j = 1; j <= 10; j++)
{
bond.Maturities.Add(new Maturity(){ID = j, BondID = i, MatDate = DateTime.Today.AddDays(j), MatAmount = 152000 * j});
}
bonds.Add(bond);
}
return bonds;
}
}
public class Bond
{
public int ID { get; set; }
public string Title { get; set; }
public List<Maturity> Maturities { get; set; }
public Bond()
{
Maturities = new List<Maturity>();
}
}
public class Maturity
{
public int ID { get; set; }
public int BondID { get; set; }
public DateTime MatDate { get; set; }
public int MatAmount { get; set; }
}
}
这个怎么样?
IEnumerable<Bond> bigBonds = bonds.Where(b => b.Maturities.Any(m => m.MatAmount > 200000));
我不确定您要寻找的是什么,但要做这样的事情就是这样:
var filteredBonds =
(
from bond in bonds
join maturity in maturities on bond.ID equals maturity.BondID
where maturity.MatAmount > 200000
select new { bond.ID, bond.Title, maturity.MatAmount, maturity.MatDate }
).ToList();
ToArray()是可选的,您可以根据需要将其保留在表格形式中。 我不太确定您要如何处理结果。
您可能还想在数据结构中分离债券和到期日。 我不认为您真的需要一个到期列表,因为您将BondID存储为到期对象的成员。 似乎有点多余,但是说实话我不使用Linq,所以也许那是要走的路。 您的来电。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.