如何从foreach获取linq的日期

时间:2015-05-27 13:42:49

标签: c# linq

我有这两个代码。第一个创建日期从今天到七天,除了周末。如何将第二个代码组合到第一个代码中。我需要从第一个代码中获取日期并将其用于与m.CreationDate进行比较。我将使用此代码:获取typeid 1和那天的每日总书数。谢谢你的回答...

    abstract class CApplication
{
    protected $config=array();

    public function __construct($config=null) {

        echo "CApplication::construct() called";

        // DO anyting with config arrray which is from /protected/config/main.php
         //$this->config = $config;

    }

}

class CWebApplication extends CApplication
{

    public function test(){

        echo "<pre>";
        print_r($this->config);
        echo "</pre>";
    }

}

$config =  array(
    "name"          =>"My Web Application",
    "components"    => array(

        "db"        => "connectionstring:..",
        "urlManage"=> array(),
    )

);

$obj =  new CWebApplication($config);

从日期获取数据:18.5.2015,19.05.2015,20.05.2015,21.05.2015,22.05.2015,25.05.2015,26.05.2015。

我试图得到:m.CreationDate == 19.05.2015和typeid == 1总书号:50

m.CreationDate == 20.05.2015和typeid == 1总书数:15

3 个答案:

答案 0 :(得分:3)

如果您将日期投入集合中,则可以在linq中使用Contains

var book = from m in  Connection.Db.Materials
       where m.TypeId == 1 && CreationDatesArray.Contains(m.CreationDate) 
       group m by m.TypeId into g
       select new { Count = g.Count()};

添加了m。正如指出

答案 1 :(得分:1)

确定。您在Dates中有日期收集。 然后你执行分组

var book = from m in Connection.Db.Materials 
           where m.TypeId == 1 
           group m by m.CreationDate into g 
           select g

然后你可以做

 var result = Dates.Select(d => new {
    Date = d, 
    Count = book.Where(g => g.Key == d).Count() }) 

result中,您可以从Dates收集来自第二个集合的日期。

答案 2 :(得分:0)

string DateString = "";
var start = DateTime.Now;
var Dates = GetBusinessDays(start,-7);
Dates.Reverse();
foreach (var date in Dates)
{   
   DateString  = DateString + "'" + date.ToShortDateString() + "',";
 } 

DateString = DateString.TrimEnd(',');

var book = from m in Connection.Db.Materials 
           where m.TypeId == 1 
           group m by m.CreationDate into g select g;
           var results = Dates.Select(d => new { Date = d.Day + "/" + d.Month + "/" + d.Year, Count = book.Where(g => g.Key.Day == d.Day && g.Key.Month == d.Month && g.Key.Year == d.Year).Count() }).ToList(); 
//put day, month and year. Because only dates  equals with ohter dates.(I need only dates not times)

string Books = "";
foreach(var r in results)
{
  Books = Books + r.Count + ',';
}

感谢大家的帮助