循环查找-字符串元素在一起
本文关键字:元素 在一起 字符串 查找 循环 | 更新日期: 2023-09-27 18:15:19
在我收到的上一个问题的帮助下,我有一个工作的linq查找,它具有每个发票的InvoiceID +产品列表:
我可以成功地循环查找(如代码所示),并显示键,但是我需要帮助显示每个键的元素列表。
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class Program
{
class InvoiceProducts
{
public int InvoiceID { get; set; }
public int ProductID { get; set; }
}
public static void Main()
{
List<InvoiceProducts> list = new List<InvoiceProducts>();
list.Add(new InvoiceProducts{ InvoiceID = 7000, ProductID=15});
list.Add(new InvoiceProducts{ InvoiceID = 7000, ProductID=10});
list.Add(new InvoiceProducts{ InvoiceID = 7000, ProductID=10});
list.Add(new InvoiceProducts{ InvoiceID = 7000, ProductID=15});
list.Add(new InvoiceProducts{ InvoiceID = 7010, ProductID=12});
list.Add(new InvoiceProducts{ InvoiceID = 7010, ProductID=20});
list.Add(new InvoiceProducts{ InvoiceID = 7010, ProductID=12});
list.Add(new InvoiceProducts{ InvoiceID = 7021, ProductID=1});
list.Add(new InvoiceProducts{ InvoiceID = 7021, ProductID=1});
var lookup = list.Select(x => new { x.InvoiceID, x.ProductID })
.Distinct()
.ToLookup(x => x.InvoiceID, x => x.ProductID);
foreach(var x in lookup)
{
Console.WriteLine(x.Key);
}
}
}
应该返回:
7000 10,15
7010 12,20
7021 1
您只需要枚举x
,它是IEnumerable<int>
,您可以使用String.Join
将有序的int
s按需要连接起来:
foreach(var x in lookup)
{
Console.WriteLine("{0} {1}", x.Key, String.Join(",", x.OrderBy(i => i)));
}
你也可以创建一个像List<int>
:
foreach(var x in lookup)
{
List<int> productList = x.ToList();
}
应该可以:-
var result = list.GroupBy(x => x.InvoiceID)
.Select(x => x.Key + "," +
String.Join(",", x.Select(z => z.ProductID).Distinct()));
工作小提琴。