2011-04-04 79 views
2

我有泛型類的列表,其中包括2字符串屬性和1名名單爲屬性的LINQ的唯一值

代碼snipnets如下:

public Class abc 
{ 
    public int ID { get; set; } 
    public String Name { get; set; } 
    List<String> myList; 
    public List<String> Subjects 
    { 
     get 
     { 
      if (myList == null) 
      { 
       myList = new List<string>(); 
      } 
      return myList; 
     }    
    } 
    public abc() 
    { 
    } 
    public abc(int id, String name, params string[] subjects) 
    { 
     Subjects.AddRange(subjects.AsEnumerable<String>()); 
     ID = id; 
     Name = name; 

    } 
} 

List<abc> myList = new List<abc>();  
myList.Add(new abc(1, "p1", "Maths", "Science")); 
myList.Add(new abc(2, "p2", "Maths", "Art")); 
myList.Add(new abc(3, "p3", "Art", "Science"));  
myList.Add(new abc(4, "p4", "Geometry", "Maths")); 

我需要的輸出

Subject Count Person 

Maths 3  p1,p2,p4 

Science 2  p1,p3 

Art  2  p2,p3 

Geometry 1  p4 

回答

4

看起來像你想要的東西,如:

var query = from item in myList 
      from subject in item.Subjects 
      group item.Name by subject into g 
      select new { Subject = g.Key, 
         Count = g.Count(), 
         Person = string.Join(",", g) }; 

(如果你使用.NET 3.5更改gg.ToArray()string.Join電話。)

+0

是的,這是我所要求的,謝謝:) – saloni 2011-04-04 08:44:47

0
var result =myList.SelectMany(p => p.Subjects 
           .Select(q => new{Person = p.Name, Subject = q, ID = p.ID})) 
          .GroupBy(p => p.Subject) 
          .Select(p => new {Name = p.Key, Count = p.Count(), Persons = p 
           .Aggregate("", (a, b) => a + b.Person 
+ ",").TrimEnd(',')}).OrderBy(p => p.Count); 

遍歷此集合,並打印結果需要 - 性能結果都是名稱,數量,人員

+0

這工作太..謝謝 – saloni 2011-04-04 08:45:14