我是C#的新手,我正在尝试使用EF和linq查询sql,从今天到特定日期返回项目列表(策略),比如提前60天,这一切都发生在类库中,然后我想循环访问控制台应用程序中的项目并列出该时间段的策略,这是我在类库中的代码。
public class Class1
{
public void DoSomething()
{
using (var context = new CRMContext())
{
context.Policies.Where(p => p.new_RenewalDate ==
DateTime.Today.AddDays(60).Date).ToList();
}
}
}
我想在控制台应用程序中调用它
public class Program
{
public static void Main(string[] args)
{
Class1 instance = new Class1();
}
}
我想使用for-each循环遍历项目并写出到控制台,我该如何归档?任何帮助将不胜感激。
答案 0 :(得分:3)
public class Class1 {
public List<Policy> DoSomething() {
using (var context = new CRMContext())
{
return context.Policies.Where(p => p.new_RenewalDate == DateTime.Today.AddDays(60).Date).ToList();
}
}
}
Class1 instance = new Class1();
List<Policy> list = instance.DoSomething();
foreach(Policy policy in list)
{
print what you want to print here :)
}
答案 1 :(得分:2)
您只需要将策略分配给变量,然后循环遍历它:
public void DoSomething()
{
using (var context = new CRMContext())
{
var targetDate = DateTime.Today.AddDays(60).Date;
var policies = context.Policies.Where(p => p.new_RenewalDate == targetDate);
foreach (var policy in policies)
{
Console.WriteLine(policy.new_RenewalDate); // etc...
}
}
}
并在您的主程序中:
public static void Main(string[] args)
{
Class1 instance = new Class1();
instance.DoSomething();
}
答案 2 :(得分:1)
您只需要从您执行该工作的方法中返回一个枚举。
public class Class1
{
// Return list if you need list functionality, otherwise enumerable will do
public IEnumerable<Policy> DoSomething()
{
using (var context = new CRMContext())
{
return context.Policies.Where(p => p.new_RenewalDate ==
DateTime.Today.AddDays(60).Date).ToList();
}
}
}
public class Program
{
public static void Main(string[] args)
{
Class1 instance = new Class1();
foreach (var item in instance.DoSomething())
{
// Do work on the item here
}
}
}