日期:2014-05-20  浏览次数:20748 次

求一条linq查询语句。
评分系统,查询6月到8月所有的评分信息,包括未评或已评分数。

环境

Table1 Table2
Name Name Month Score
----------- --------------------- 
A A 8 35
B B 8 45
C C 8 54
  C 7 78

期望的查询结果:
Name Month Score
A 6 NA
A 7 NA
A 8 35
B 6 NA
B 7 NA
B 8 45
C 6 NA
C 7 78
C 8 54

注:已评分的显示分数,没有评分的显示“NA”。

不知道说清楚没,对linq不是很了解。

------解决方案--------------------
C# code
var ay=new int[]{6,7,8};

var query=from t1 in Table1
          join t2 in Table2.Where(s=>ay.Contains(s.Month))
          on t1.Name equals t2.Name into t
          from t2 in t.DefaultIfEmpty()
          from x in ay 
          orderby t2.Name,t2.Month
          select new Table2
           {
             Name=t1.Name,
             Month=x,
             Score=t2==null?"NA":t2.Score
           };

------解决方案--------------------
楼上好像不对呀。

以下是我的,替换成Table1 和 Table2就可以了。
C# code

class CJoin
{
    class T
    {
        public string Name { get; set; }
        public int Month { get; set; }
        public string Score { get; set; }

        public static T FromString(string s)
        {
            string[] ss = s.Split(' ');

            return new T
            { Name = ss[0], Month = int.Parse(ss[1]), Score = ss[2]};
        }

        public override string ToString()
        {
            return string.Format("{0}\t{1}\t{2}", Name, Month, Score); 
        }
    }

    static void Test()
    {
        List<string> names = new List<string>();

        for (char c = 'A'; c <= 'C'; c++)
        {
            names.Add(c.ToString());
        }

        int[] months = new int[] {6, 7, 8};
        var d1 = from n in names
                from m in months
                    select new { Name = n, Month = m};

        string s = "A 8 35|B 8 45|C 8 54|C 7 78";
        List<T> d2 = new List<T>();

        string[] ss = s.Split('|');

        foreach (var n in ss)
        {
            d2.Add(T.FromString(n));
        }

        var query2 = from left in d1
                        join right in d2 on new { left.Name, left.Month }
                        equals new { right.Name, right.Month } into gp
                        from item in gp.DefaultIfEmpty()
                        select new T
                        {
                            Name = left.Name,
                            Month = left.Month,
                            Score = item == null ? "NA" : item.Score
                        };

        foreach (var t in query2)
        {
            Trace.WriteLine(t.ToString());
        }
    }
}