2017-04-17 56 views
1

我有一個存儲過程是這樣的:如何將結果集與linq進行分組?

SELECT UrlId, TypeId, DomainId, Url, d.OrgId AS orgId 
FROM SystemUrls 
JOIN Domaindata d ON d.Id = DomainId 

它給了我這樣的結果:

enter image description here

enter image description here

在這個貌似代碼

我想要什麼:

將在domainId 上分組此結果,以便我得到兩行。

我有這個類:

public class TestModel 
{ 
    public long DomainId { get; set; } 
    public List<SystemUrl> Urls { get; set; } 
} 

我想獲得像resul:

域ID 79 Urls.count()= 2

域ID 81 Urls.COunt = 2

我的嘗試:

   var t = 
       (from u in urls 
        select 
        new TestModel 
        { 
         DomainId = u.DomainId, 
         Urls = new List<SystemUrl> {new SystemUrl {Url = u.Url}} 
        }).GroupBy(v => v.DomainId).ToList(); 

的問題是,我似乎得到域ID的權利,但沒有其他數據似乎遵循:

enter image description here

我該如何解決這個問題?

回答

2
var t = urls.GroupBy(u => u.DomainId) 
    .Select(g => new TestModel{ 
     DomainId = g.Key, 
     Urls = g.Select(u => new SystemUrl {Url = u.Url}).ToList() 
    }) 
    .ToList(); 
+0

linq並不是我的強項,現在我覺得我應該能夠弄清楚這一點。謝謝 – ThunD3eR

+0

@ Ra3IDeN - 樂於提供幫助。 – Igor

2

這裏是你如何能做到這:

var t = urls.GroupBy(v => v.DomainId).Select(g => new TestModel 
{ 
    DomainId = g.Key, 
    Urls = g.Select(u => new SystemUrl {Url = u.Url}).ToList() 
}).ToList(); 
+0

謝謝! Linq並不是我的強項,並且看到了兩個給出的答案,我覺得我應該能夠弄清楚這一點,但是我的思考過程有點偏離。 – ThunD3eR

+0

你非常接近。 –

0

將DataAdapter的reults到數據表。然後使用以下內容:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Data; 




namespace ConsoleApplication49 
{ 
    class Program 
    { 

     static void Main(string[] args) 
     { 
      DataTable dt = new DataTable(); 
      dt.Columns.Add("Urld", typeof(int)); 
      dt.Columns.Add("Typeid", typeof(int)); 
      dt.Columns.Add("DomainId", typeof(int)); 

      dt.Rows.Add(new object[] { 13, 1, 79 }); 
      dt.Rows.Add(new object[] { 14, 2, 79 }); 
      dt.Rows.Add(new object[] { 15, 2, 81 }); 
      dt.Rows.Add(new object[] { 16, 1, 81 }); 

      var results = dt.AsEnumerable() 
       .GroupBy(x => x.Field<int>("DomainID")) 
       .ToDictionary(x => x.Key, y => y.Count()); 

     } 


    } 

}