簡體   English   中英

訪問List中保存的對象屬性 <T> 經過LINQ小組程序

[英]Accesing object properties held in List<T> after LINQ group by procedure

我有一個List<T> ,它持有幾個名為tc的類型為TwitterCollection對象。 每個tc實例包含5個屬性。

TwitterCollection類看起來像這樣:

public class TwitterCollection
{
    public string origURL { get; set; }
    public string txtDesc { get; set; }
    public string imgURL { get; set; }
    public string userName { get; set; }
    public string createdAt { get; set; }

}

我正在運行Linq to objects語句:

    var counts = from tc in sList
                 group tc by tc.origURL into g
                 orderby g.Count()
                 select new { myLink = g.Key, Count = g.Count() };

現在我遇到的問題是我無法訪問任何tc屬性。 我可以訪問origURL沒問題,因為它被分配給g ...但是txtDescimgURL和其他屬性似乎無法訪問。 我需要上面的語句才能對數據進行適當的排序。

如何修改我的Linq語句以包含tc所有其他屬性,以及它仍然按照現在的方式按Count()排序/排序。

您已對結果進行分組 - 您希望獲得哪個用戶名? 該組是一整個元素序列 ,所有元素都具有相同的URL。 如果你想使用第一個,你可以這樣做:

var counts = from tc in sList
             group tc by tc.origURL into g
             orderby g.Count()
             select new { myLink = g.Key, First = g.First(), Count = g.Count() };

然后你可以這樣做:

foreach (var group in counts)
{
    Console.WriteLine(group.First.userName);
}

如果你想要整個組,那么只需選擇它:

var counts = from tc in sList
             group tc by tc.origURL into g
             orderby g.Count()
             select new { Group = g, Count = g.Count() };

不可否認的是,在單獨Count沒有多大意義 - 你可以這樣做:

var groups = sList.GroupBy(tc => tc.origURL)
                  .OrderBy(g => g.Count());

然后你可以使用:

foreach (var group in groups)
{
    int count = group.Count();
    var key = group.Key;
    foreach (var entry in group)
    {
        // Use each item in the group, etc.
    }
}

問題是您已經有效地丟棄了組中的所有項目。 你需要以某種方式維護這些信息。 例如:

var groups = from tc in sList 
             group tc by tc.origURL into g 
             orderby g.Count() 
             select new { myLink = g.Key, Items = g }; 

foreach(var group in groups) {
    Console.WriteLine("Link: {0}, Count: {1}", group.myLink, group.Items.Count());
    foreach(var item in group.Items) {
        Console.WriteLine(item.txtDesc);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM