从通用列表中简单选择

时间:2011-07-12 07:37:43

标签: c# linq list

我有一个清单:

List<Product> allProducts = new List<Product>();

产品可以具有相同的显示名称,但URL不同:s。我想做的是获得每个产品的所有网址。

foreach (Product p in allProducts.Distinct().ToList())
    {
        string displayname = p.GetDisplayName();
        string url = p.GetPublishedUrls()[0];
    }

但我坚持到这里。任何帮助表示赞赏!

5 个答案:

答案 0 :(得分:1)

使用GroupBy:

foreach (var productGroup in allProducts.GroupBy(p => p.GetDisplayName()) {
    # productGroup.Key is the display name
    # and productGroup enumerates all the products for the display name
}

答案 1 :(得分:0)

你想要这个:

List<string> allUrls = allProducts.SelectMany(p => p.GetPublishedUrls()).ToList();

答案 2 :(得分:0)

给SelectMany一个 - 如果我正确读取你的代码片段,这应该返回一个IEnumerable。

IEnumerable<string> publishedUrls = allProducts.SelectMany(p => p.GetPublishedUrls());

答案 3 :(得分:0)

我不太清楚我理解你的问题,但是如果你试图创建一个列表,其中每个项目都有产品显示名称和网址,那么这就是代码:

var res = from p in products.AsQueryable()                       选择新的{ProductName = p.Name,ProductUrls = p.Urls};

答案 4 :(得分:0)

代码:

 class Product
 {
     public string DisplayName;
     public string URL;
 }


 List<Product> allProducts = new List<Product>();

 allProducts.Add(new Product { DisplayName = "A", URL = "A1" });
 allProducts.Add(new Product { DisplayName = "A", URL = "A2" });
 allProducts.Add(new Product { DisplayName = "A", URL = "A3" });

 allProducts.Add(new Product { DisplayName = "B", URL = "B1" });
 allProducts.Add(new Product { DisplayName = "B", URL = "B3" });

 var pGroups = from p in allProducts
               group p by p.DisplayName into g
               select new { DisplayName = g.Key, URLList = g };

 foreach (var p in pGroups)
 {
       Console.WriteLine("Product Name: " + p.DisplayName);
       foreach (var u in p.URLList)
       {
           Console.WriteLine("  URL: " + u.URL);
       }
 }

输出:

Product Name: A
  URL: A1
  URL: A2
  URL: A3
Product Name: B
  URL: B1
  URL: B3