Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从通用列表中进行简单选择_C#_Linq_List - Fatal编程技术网

C# 从通用列表中进行简单选择

C# 从通用列表中进行简单选择,c#,linq,list,C#,Linq,List,我有一份清单: List allProducts=new List() 这些产品可以有相同的显示名,但URL:s不同。我想做的是获得每个产品的所有URL foreach (Product p in allProducts.Distinct().ToList()) { string displayname = p.GetDisplayName(); string url = p.GetPublishedUrls()[0]; } 但是我被困在这里了。

我有一份清单:

List allProducts=new List()

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

foreach (Product p in allProducts.Distinct().ToList())
    {
        string displayname = p.GetDisplayName();
        string url = p.GetPublishedUrls()[0];
    }
但是我被困在这里了。感谢您的帮助

您想要这个:

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

尝试一下SelectMany-如果我正确阅读了您的代码片段,应该会返回一个IEnumerable

IEnumerable<string> publishedUrls = allProducts.SelectMany(p => p.GetPublishedUrls());
IEnumerable publishedUrls=allProducts.SelectMany(p=>p.GetPublishedUrls());
使用分组方式:

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
}

我不太确定我是否理解您的问题,但如果您试图创建一个列表,其中每个项目都有产品显示名称和URL,下面是代码:

var res=来自products.AsQueryable()中的p 选择新建{ProductName=p.Name,ProductUrls=p.Urls}

代码:

 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);
       }
 }

我不确定我是否理解你的问题。你是说你有产品A,B,C,其中A有URL(A1,A2,A3),B有URL(B2,B3,B4,B5),C有URL(C2,C3)?那么,您想要什么作为输出?
Product Name: A
  URL: A1
  URL: A2
  URL: A3
Product Name: B
  URL: B1
  URL: B3