2013-12-24 4 views
0

У меня есть collectionof товары со следующей структуройКак получить этот результат с помощью LINQ

var results= [ 

{3   2013  5644.57127629528}, 
{9   2013  5352.08258069403}, 

{1   2013  5644.81057603413}, 
{10   2013  170.013936031616}, 
{4   2013  5383.75537735399}, 
{6   2013  5413.9359165467}, 
{7   2013  5625.75008073717}, 
{2   2013  5015.54442930293}, 
{8   2013  5534.53627550067}, 
{5   2013  5538.10984479548}, 
{4   2012  5438.81051077828}, 
{1   2012  5585.21099483651} 
{11   2012  5325.79426499073} 
{12   2012  5683.07184047395}, 
{6   2012  5366.00634837989}, 
{7   2012  5580.53474782527}, 
{3   2012  5615.08714653137}, 
{9   2012  5435.35217403032}, 
{8   2012  5579.6929459533}, 
{2   2012  5175.35027960843} 
{10   2012  5556.99197086551}, 
{5   2012  5575.47039317314}, 
{10   2011  5512.31976625987}, 
{12   2011  5669.3365148545}, 
{11   2011  5356.42306696735} 

] 

месяц, год, Totalkwh (usageModel) (его табличное представление значения объекта, на самом деле у меня есть коллекция объектов с этим значением в моем Memmory)

из этой коллекции я хочу, чтобы получить набор результатов, которые выглядят как следующая структура

[{10   2013  170.013936031616 10   2012  5556.99197086551},{9  2013 5352.08258069403 9   2012  5435.35217403032 }, 

{8   2013  5534.53627550067 8   2012  5579.6929459533}, {7   2013  5625.75008073717 7   2012  5580.53474782527}, 

{6   2013  5413.9359165467 6   2012  5366.00634837989} ,{5   2013  5538.10984479548 5   2012  5575.47039317314}, 

{4   2013  5383.75537735399 4   2012  5438.81051077828},{3   2013  5644.57127629528 3   2012  5615.08714653137}, 

{2   2013  5644.81057603413 2   2012  5175.35027960843}, {1   2013  5644.81057603413, 1   2012  5585.21099483651}, 

{12   2012  5683.07184047395 12   2011  5669.3365148545 },{11   2012  5325.79426499073, 11   2011  5356.42306696735}, 

{10   2012  5556.99197086551 10   2011  5512.31976625987 }] 

leftMonth, leftYear, leftValue rightMonth, rightYear, rightValue (reportModel)

Основные Примечания: Пожалуйста, посмотрите данные путь, сгруппированных на основе месяца и двух adjecent лет формируется левая правая часть

Как я могу сделать это использование linq или любых других механизмов

+0

Что такое структура объекта? не вывести его из приведенного выше примера. – TutuGeorge

ответ

0

Простой способ сделать это, хотя и не обязательно наиболее результативным:
(это вернет -1 как правое значение в течение нескольких месяцев, у которого нет соответствующего месяца в следующем году. Вы можете отфильтровать те из потом, если вам не нужны те)

var groupedResults = results.Select(r=> new 
    { 
     leftMonth = r.Month, 
     leftYear = r.Year, 
     leftKwh = r.Totalkwh, 
     rightMonth = r.Month, 
     rightYeahr = r.Year+1, 
     rightKwh = results 
      .Where(r2=>r2.Year == r.Year + 1 && r2.Month == r.Month) 
      .Select(r2=>rs.totalkwh) 
      .DefaultIfEmpty(-1) 
      .First(), 
    }); 

results.Select(r=> 

Я предполагаю, что ваши объекты содержат год и месяц, как int (хотя вы можете рассмотреть возможность использования DateTime вместо)

+0

Уловное решение, но имеет небольшое влияние на производительность .. Но мой случай максимальный счетчик коллекции равен 24, поэтому это не будет проблемой –

0

Я Я боюсь, что нет прямого запроса LINQ, чтобы делать то, что вы хотели. Кстати, вышеприведенный ответ не даст желаемого результата! В любом случае взгляните на этот ответ тоже.

public class Structure 
{ 
    public int Month; 
    public int Year; 
    public double Totalkwh; 
} 

public class CombinedStructure 
{ 
    public int LM; 
    public int LY; 
    public double LT; 
    public int RM; 
    public int RY; 
    public double RT; 
} 
     List<Structure> structures = new List<Structure>(); 
     structures.Add(new Structure() { Month = 3, Year = 2013, Totalkwh = 5644.57127629528 }); 
     structures.Add(new Structure() { Month = 9, Year = 2013, Totalkwh = 5352.08258069403 }); 
     structures.Add(new Structure() { Month = 1, Year = 2013, Totalkwh = 5644.81057603413 }); 
     structures.Add(new Structure() { Month = 10, Year = 2013, Totalkwh = 170.013936031616 }); 
     structures.Add(new Structure() { Month = 4, Year = 2013, Totalkwh = 5383.75537735399 }); 
     structures.Add(new Structure() { Month = 6, Year = 2013, Totalkwh = 5413.9359165467 }); 
     structures.Add(new Structure() { Month = 7, Year = 2013, Totalkwh = 5625.75008073717 }); 
     structures.Add(new Structure() { Month = 2, Year = 2013, Totalkwh = 5015.54442930293 }); 
     structures.Add(new Structure() { Month = 8, Year = 2013, Totalkwh = 5534.53627550067 }); 
     structures.Add(new Structure() { Month = 5, Year = 2013, Totalkwh = 5538.10984479548 }); 
     structures.Add(new Structure() { Month = 4, Year = 2012, Totalkwh = 5438.81051077828 }); 
     structures.Add(new Structure() { Month = 1, Year = 2012, Totalkwh = 5585.21099483651 }); 
     structures.Add(new Structure() { Month = 11, Year = 2012, Totalkwh = 5325.79426499073 }); 
     structures.Add(new Structure() { Month = 12, Year = 2012, Totalkwh = 5683.07184047395 }); 
     structures.Add(new Structure() { Month = 6, Year = 2012, Totalkwh = 5366.00634837989 }); 
     structures.Add(new Structure() { Month = 7, Year = 2012, Totalkwh = 5580.53474782527 }); 
     structures.Add(new Structure() { Month = 3, Year = 2012, Totalkwh = 5615.08714653137 }); 
     structures.Add(new Structure() { Month = 9, Year = 2012, Totalkwh = 5435.35217403032 }); 
     structures.Add(new Structure() { Month = 8, Year = 2012, Totalkwh = 5579.6929459533 }); 
     structures.Add(new Structure() { Month = 2, Year = 2012, Totalkwh = 5175.35027960843 }); 
     structures.Add(new Structure() { Month = 10, Year = 2012, Totalkwh = 5556.99197086551 }); 
     structures.Add(new Structure() { Month = 5, Year = 2012, Totalkwh = 5575.47039317314 }); 
     structures.Add(new Structure() { Month = 10, Year = 2011, Totalkwh = 5512.31976625987 }); 
     structures.Add(new Structure() { Month = 12, Year = 2011, Totalkwh = 5669.3365148545 }); 
     structures.Add(new Structure() { Month = 11, Year = 2011, Totalkwh = 5356.42306696735 }); 

     List<CombinedStructure> combinedStructures = new List<CombinedStructure>(); 
     foreach (var groupedStructure in structures.OrderByDescending(s => s.Year).GroupBy(s => s.Month)) 
     { 
      var orderedGroup = groupedStructure.GetEnumerator(); 
      orderedGroup.MoveNext(); 
      while (true) 
      { 
       Structure firstStructure = orderedGroup.Current; 
       Structure secondStructure; 
       if (orderedGroup.MoveNext()) 
       { 
        secondStructure = orderedGroup.Current; 
        combinedStructures.Add(
         new CombinedStructure() 
         { 
          LM = firstStructure.Month, 
          LY = firstStructure.Year, 
          LT = firstStructure.Totalkwh, 
          RM = secondStructure.Month, 
          RY = secondStructure.Year, 
          RT = secondStructure.Totalkwh 
         } 
        ); 
       } 
       else 
       { 
        break; 
       } 
      } 
     } 

Для удобства я создал два строго типизированных классов (Structure и CombinedStructure), а также вставлены вам данные в список Structure. Надеюсь, это поможет.

0

Вот еще один способ. Я назвал класс, содержащий каждый набор данных Usage. Как только данные были в списке, я использовал выражение linq для первого порядка списка по месяцам по возрастанию, а затем по убыванию. Группировка по месяцу и разливочных каждую группу в списке, бросая весь результат в списке, мы в конечном итоге с 2d списка List> заказанного месяц затем год по убыванию:

List<Usage> results = new List<Usage> 
{ 
    {new Usage{Month = 3, Year = 2013, Kwh = 5644.57127629528}}, 
    {new Usage{Month = 9, Year = 2013 , Kwh = 5352.08258069403}}, 
    {new Usage{Month = 1, Year = 2013, Kwh = 5644.81057603413}}, 
    {new Usage{Month = 10, Year = 2013, Kwh = 170.013936031616}}, 
    {new Usage{Month = 4, Year = 2013, Kwh = 5383.75537735399}}, 
    {new Usage{Month = 6, Year = 2013, Kwh = 5413.9359165467}}, 
    {new Usage{Month = 7, Year = 2013, Kwh = 5625.75008073717}}, 
    {new Usage{Month = 2, Year = 2013, Kwh = 5015.54442930293}}, 
    {new Usage{Month = 8, Year = 2013, Kwh = 5534.53627550067}}, 
    {new Usage{Month = 5, Year = 2013, Kwh = 5538.10984479548}}, 
    {new Usage{Month = 4 , Year = 2012, Kwh = 5438.81051077828}}, 
    {new Usage{Month = 1, Year = 2012, Kwh = 5585.21099483651}}, 
    {new Usage{Month = 11, Year = 2012, Kwh = 5325.79426499073}}, 
    {new Usage{Month = 12, Year = 2012, Kwh = 5683.07184047395}}, 
    {new Usage{Month = 6, Year = 2012, Kwh = 5366.00634837989}}, 
    {new Usage{Month = 7, Year = 2012, Kwh = 5580.53474782527}}, 
    {new Usage{Month = 3, Year = 2012, Kwh = 5615.08714653137}}, 
    {new Usage{Month = 9, Year = 2012, Kwh = 5435.35217403032}}, 
    {new Usage{Month = 8, Year = 2012, Kwh = 5579.6929459533}}, 
    {new Usage{Month = 2, Year = 2012, Kwh = 5175.35027960843}}, 
    {new Usage{Month = 10, Year = 2012, Kwh = 5556.99197086551}}, 
    {new Usage{Month = 5, Year = 2012, Kwh = 5575.47039317314}}, 
    {new Usage{Month = 10, Year = 2011, Kwh = 5512.31976625987}}, 
    {new Usage{Month = 12, Year = 2011, Kwh = 5669.3365148545}}, 
    {new Usage{Month = 11, Year = 2011, Kwh = 5356.42306696735}} 
}; 
List<List<Usage>> newresults = (from u in results.OrderBy(x => x.Month).ThenByDescending(y => y.Year) 
    group u by u.Month into g 
    select g.ToList()).ToList(); 

public class Usage 
{ 
    public int Year = 0; 
    public int Month = 0; 
    public double Kwh = 0; 
    public override string ToString() 
    { 
     return "Month = " + Month.ToString() + 
      ", Year = " + Year.ToString() + 
      ", Kwh = " + Kwh.ToString(); 
    } 
} 

С в ToString переопределения можно форматировать выход как вам нравится:

?newresults[0] 
Count = 2 
    [0]: {Month = 1, Year = 2013, Kwh = 5644.81057603413} 
    [1]: {Month = 1, Year = 2012, Kwh = 5585.21099483651} 
?newresults[1] 
Count = 2 
    [0]: {Month = 2, Year = 2013, Kwh = 5015.54442930293} 
    [1]: {Month = 2, Year = 2012, Kwh = 5175.35027960843} 
?newresults[2] 
Count = 2 
    [0]: {Month = 3, Year = 2013, Kwh = 5644.57127629528} 
    [1]: {Month = 3, Year = 2012, Kwh = 5615.08714653137} 
?newresults[3] 
Count = 2 
    [0]: {Month = 4, Year = 2013, Kwh = 5383.75537735399} 
    [1]: {Month = 4, Year = 2012, Kwh = 5438.81051077828} 
?newresults[4] 
Count = 2 
    [0]: {Month = 5, Year = 2013, Kwh = 5538.10984479548} 
    [1]: {Month = 5, Year = 2012, Kwh = 5575.47039317314} 
Смежные вопросы