顯示具有 LINQ 標籤的文章。 顯示所有文章
顯示具有 LINQ 標籤的文章。 顯示所有文章

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));
   }

  }

 }
}


執行結果:

2015/01/28

C#.Net LINQ select new

Select new可以將資料取出,並且放入集合內
該集合可以自訂該屬性名稱

Code:
using System;
using System.Windows.Forms;
using System.Linq;
namespace Sample
{
    public partial class Form1 : Form
    {
        String[] names = { "a", "b", "c", "d", "e","f","g","h" };

        public Form1()
        {
            InitializeComponent();
            var gp = from n in names
                     select new
                     {
                         name = n,
                         index = Array.FindIndex(names, f => f.Contains(n))
                     };

            foreach (var g in gp)
                textBox1.Text += String.Format("{0}={1}{2}", 
                    g.index, g.name, Environment.NewLine);
        }

    }

}


執行結果:

C#.Net 使用LINQ做交集和聯集

Code:
using System;
using System.Windows.Forms;
using System.Linq;
namespace Sample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int[] number1 = { 1, 13, 55, 1, 88, 95, 33, 55, 1, 44, 100 };
        int[] number2 = { 1, 22, 44, 8, 66, 100, 5, 1, 1, 95 };

        /// <summary>
        /// 交集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            foreach (int number in (number1.Intersect(number2)
                .OrderBy(x => x > 0 ? x : int.MinValue)))
                textBox1.Text += number + Environment.NewLine;
        }

        /// <summary>
        /// 聯集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            foreach (int number in number1.Union(number2)
                .OrderBy(x => x > 0 ? x : int.MinValue))
                textBox1.Text += number + Environment.NewLine;
        }

    }

}

執行結果:

交集

聯集

2013/11/20

C# Parallel 平行化處理

平行處理就是將資料集切割成較小的區塊,讓多個執行緒同時處理不一樣區塊




using System;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {

            for (int i = 0; i < 10000; i++)
            {
                for (int j = 1; j < i; j++)
                {
                    Console.Write(j + i);
                }
                Console.WriteLine();
            }

            Console.WriteLine("正常執行緒結束");
            Console.ReadKey();

            Parallel.For(0, 10000, ctr =>
            {
                for (int i = 0; i < ctr; i++)
                {
                    for (int j = 1; j < i; j++)
                    {
                        Console.Write(j + i);
                    }
                    Console.WriteLine();
                }
            });
            Console.WriteLine("平行化處理結束");
            Console.ReadKey();
        }
    }
}


以正常方式去計算:

2013/11/15

C#.Net LINQ

五年前,去書局有看到LINQ的書…對它不熟,沒買
三年前,學長叫我去學LINQ,問學長說那你會嗎?他說:不會…哪招?
最近覺得用LINQ可以簡化許多工作,所以學啦XD


何謂LINQLINQ全名為『Language-Integrated Query』,LINQ是在VS 2008和.Net 3.5所推出的一項新功能

LINQ以簡單的字樣搜尋想要的物件,並且透過LINQ變成C#以及VB的第一級語言
想要深入探討可以參考這篇『LINQ 簡介』,注意LINQ在搜尋物件是有限制的

以下程式碼是參考『LINQ 查詢簡介』而來的


using System;
using System.Linq;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            int[] numbers = new int[10] { 20, 11, 74, 23, 54, 10, 99, 88, 77, 46 };

            var numQuery = from num in numbers where (num % 2) == 0 select num;
            foreach (int num in numQuery)
            {
                Console.WriteLine(num);
            }

            Console.ReadKey();
        }
    }
}

可以知道該程式有個陣列,透過var這個強型別去接收LINQ所搜尋出來的結果
常與資料庫做溝通的人一定很熟悉SELECT FROM WHERE等字眼

資料來源從num指到numbers,並搜尋num是為2的倍數,如果是就包含近來
var numQuery = from num in numbers where (num % 2) == 0 select num;

並透過foreach走訪強型別的數值,用強型別好處在於可以取代任何型別,不用因為型別的不一樣無法接受值,進而造成型別錯誤




參考資料:
http://msdn.microsoft.com/zh-tw/library/bb397926(v=vs.90).aspx
http://msdn.microsoft.com/zh-tw/library/bb397897(v=vs.90).aspx
http://msdn.microsoft.com/zh-tw/library/bb397906(v=vs.90).aspx