2016/08/26

C#.Net LINQ選擇多重欄位

以下這個範例有兩個結構分別是學生以及分數
兩者相同之處在於結構內都有學生的姓名
所以我們用學生的姓名來判斷是否相同
如果相同則透過new方法來宣告為新的結構以及加入該值


using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace Test
{
 public partial class Form1 : Form
 {
  /// <summary>
  /// Logger
  /// </summary>
  private static readonly ILog LOG = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);

  struct Student
  {
   public string name;
  }

  struct Score
  {
   public string name;

   public int math;

   public int ch;

   public int en;
  }

  List<Student> listS = new List<Student>();

  List<Score> listC = new List<Score>();

  public Form1()
  {
   InitializeComponent();
   //初始化Log4Net
   log4net.Config.XmlConfigurator.Configure();

   listS.Add(new Student() { name = "王曉" });
   listS.Add(new Student() { name = "小名" });
   listS.Add(new Student() { name = "鵜鶘" });

   listC.Add(new Score() { name = "王曉", math = 70, ch = 50, en = 100 });
   listC.Add(new Score() { name = "小名", math = 50, ch = 30, en = 1 });


   var listT = from s in listS
      from c in listC
      where s.name.Equals(c.name)
      select new
      {
       s.name,
       c.math,
       c.en,
       c.ch,
       score = (c.math + c.en + c.ch / 3)
      };
   foreach (var t in listT)
   {
    LOG.Info(String.Format("{0} avg:{1}", t.name, t.score));
   }

  }

 }
}


執行結果: