2017-06-14 9 views
1

空のレコードを再調整し、ギャップを " - "で埋めるために私のforeachに助けが必要です。C#空のレコードを埋める

のは、我々は場合は30分、45分、90分、120分ではなく60分を持っているとしましょう:

それは、各IDの合計レコード数を数えるのが最大5で言わせて、30分、45分、60分、90分することができますそして120分。

3がある場合は、欠落していて「 - 」で埋めることができます。

スクリプトの同じイデア。

List<Treatment> treatment = new List<Treatment>(); 
treatment.Add(new Treatment { id = 1, treatmentNameId = 11, duration = "30", price = 30 }); 
treatment.Add(new Treatment { id = 1, treatmentNameId = 11, duration = "45", price = 45 }); 
treatment.Add(new Treatment { id = 1, treatmentNameId = 11, duration = "60", price = 60 }); 
treatment.Add(new Treatment { id = 1, treatmentNameId = 2, duration = "30", price = 30 }); 
//treatment.Add(new Treatment { id = 1, treatmentNameId = 2, duration = "45", price = 45 }); 
treatment.Add(new Treatment { id = 1, treatmentNameId = 2, duration = "60", price = 60 }); 

var newList = (from t in treatment 
         select t) 
         .AsQueryable().ToList(); 

List<List> newList= new List<List>(); 
foreach (var item in newList) 
{  
    if (item.duration == "30") 
    { 
     newList.Add(new List { treatmentNameId = item.treatmentNameId, thirtyMin = "30" }); 
    } 

    if (item.duration == "45") 
    { 
     newList.Add(new List { treatmentNameId = item.treatmentNameId, fortyFive= "45" }); 
    }     

    if (item.duration == "60") 
    { 
     newList.Add(new List { treatmentNameId = item.treatmentNameId, sixty= "60" });   
    } 
} 

最終結果は...

id:1 30, 45, 60, - 
id:2 30, - , 60, 90 
id:3 - , 45, -, 90 

など、などの助けを

多くの多くのおかげで何かをしたいとすべきです。

答えて

0

私はすべてこれについて非常に詳細な説明はしませんが、概念的には私は単にtreatmentNameIdでグループ化して、SQLの外部結合と非常によく似たことをやっています。期間の間、グループ参加が空になったら、期間の代わりに「 - 」を選択します。簡潔さのために匿名型を使用する。

 var durations = new[] {"15", "30", "45", "60"}; 

     var results = treatments 
      .GroupBy(t => t.treatmentNameId).Select(group => new 
      { 
       treatmentNameId = group.Key, 
       durations = durations.GroupJoin(group, s => s, g => g.duration, 
        (s, grouping) => !grouping.Any() ? "-" : s) 
      }); 

     foreach (var result in results) 
     { 
      Console.WriteLine(result.treatmentNameId + ": " + string.Join(", ", result.durations)); 
     } 

これは、その結果:あなたはより具体的な何かに問題がある場合、私はさらに説明させていただき

11: -, 30, 45, 60 
2: -, 30, -, 60