按两个具有混合值的条件对值进行分组

时间:2013-06-06 21:05:51

标签: c# .net linq

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

  <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 值4。

困难在于它可以混合,其值为4:“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();

2 个答案:

答案 0 :(得分:2)

我将尝试回答,但目前还不完全清楚你的目标是什么。如果您尝试获取一组对象并为每个value3生成一个对象,其中每个生成的对象都具有属性DateIn =(MIN value1,其中value4 =“IN”)和DateOut =(MAX value1其中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()
           }

答案 1 :(得分: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()
             });