3

我有一个包含以下值的列表:

  <event>
    <value1>2013-05-04 10:00:00.123Z</value1>
    <value2>1111</value2>
    <value3>303533F1700DEE80001E8482</value3>
    <value4>IN</value4>
  </event> 

  <event>
    <value1>2013-05-04 10:00:00.123Z</value1>
    <value2>1111</value2>
    <value3>303533F1700DEE80001E8482</value3>
    <value4>OUT</value4>
  </event> 

我需要对value3值进行分组并获得Distincts value4。

困难在于它可以与 value4 混合,例如:“OUT, OUT, IN, OUT, IN, IN”。

这可以在Linq中做到吗?!

到目前为止我得到了这个:

 var s = (from p in trackingList
                group p by new {p.value3}
                into grp
                select new TrackingSteps
                    {
                        DateIn = **grp.Key.value1**,
                        DateOut = 'the **value1** of **value4**'

                    }).ToList();
4

2 回答 2

2

我将尝试一个答案,但并不完全清楚你要做什么。如果您尝试获取一组对象并为每个 value3 生成一个对象,其中每个生成的对象都有属性 DateIn = (MIN value1 where value4 = "IN") 和 DateOut = (MAX value1 where value4 = "OUT "),那么它可能看起来像这样:

from p in trackingList
group p by p.Value3 into g
select new {
               Value3 = g.Key,
               DateIn = g.Where(o => o.Value4 == "IN")
                         .Select(o => o.Value1)
                         .DefaultIfEmpty(DateTime.MinValue)
                         .Min(),
               DateOut = g.Where(o => o.Value4 == "OUT")
                          .Select(o => o.Value1)
                          .DefaultIfEmpty(DateTime.MaxValue)
                          .Max()
           }
于 2013-06-06T21:37:09.170 回答
1

此 LINQ 查询按 Value3 分组,并为每个组选择不同的 Value4

var result = trackingList.Descendants("event")
            .Select(E => new { Value1 = E.Element("value1").Value,
                               Value3 = E.Element("value3").Value, 
                               Value4 = E.Element("value4").Value })
            .GroupBy(g => g.Value3)
            .Select(g => new { 
                 Value3 = g.Key, 
                 //DistintValue4 = g.Select(x => x.Value4).Distinct(),
                 DateIn = g.Where(x => x.Value4 == "IN").Select(x => x.Value1).FirstOrDefault(),
                 DateOut = g.Where(x => x.Value4 == "OUT").Select(x => x.Value1).FirstOrDefault()
             });
于 2013-06-06T21:10:10.423 回答