gpt4 book ai didi

c# - 如何根据日期合并两个列表

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:07:36 25 4
gpt4 key购买 nike

我有两个字符串列表,第一个列表包含对应第二个列表每个元素的 ID。列表的定义,

IdsList ["Id1","Id2"]
ShippingsNoList ["n1,n2..","t1,t2"]

表示n1,n2->Id1, t1,t2->Id2

IdsList 格式 -> A-date-BShippingNumbersList 格式-> number1,number2,etc.

我的目的是组合两个列表并将结果作为字符串返回。如果我发现 ShippingNumber 等于另一个 ShippingNumber(s) 并且它们的 Id 的日期 也应该匹配,那么我应该采用 Shipping Number 和相关的 ID。一个发货编号可能已经分配了多个相同日期的 ID。示例:

IdsList=["A-28.03.18-B", 
"S-17.05.18-G",
"L-17.05.18-P",
"M-28.03.18-T",
"B-17.05.18-U"]

ShippingNumbersList=["100,200,300",
"100,900",
"200,300,100",
"100,900,300",
"100,300"]

预期结果:

100-> A-28.03.18-B,M-28.03.18-T
300-> A-28.03.18-B,M-28.03.18-T
100-> S-17.05.18-G,L-17.05.18-P,B-17.05.18-U
300-> L-17.05.18-P, B-17.05.18-U

最佳答案

试试这个 LINQ“美”。

var idsList = new string[]
{
"A-28.03.18-B",
"S-17.05.18-G",
"L-17.05.18-P",
"M-28.03.18-T",
"B-17.05.18-U"
};

var shippingNumbersList = new string[]
{
"100,200,300",
"100,900",
"200,300,100",
"100,900,300",
"100,300"
};

var data = idsList
.Zip(shippingNumbersList, (x, y) =>
{
//parse the entry of the idsList ('x') in a dateTime
var date = DateTime.Parse(x.Split("-")[1]); //<-- may need to use DateTime.ParseExact(x.Split('-')[1], "dd.MM.yy", CultureInfo.InvariantCulture) - depending on the culture you are using, this will now work on any machine

//parse the entry of the shippingNumbersList ('y') in a IEnumerable<int>
var numbers = y.Split(",").Select(int.Parse);

//make a IEnumerable of the two different data, consisting of (Id, Date, ShippingNumber) <- a single ShippingNumber, thats why we call numbers.Select
return numbers.Select(number => (Id: x, Date: date, ShippingNumber: number));
}) //<-- use ZIP to combine the two lists together
.SelectMany(x => x) //<-- use SELECTMANY to get a flat list of each "id" with the x number of "shippingNumberList"
.GroupBy(x => (Date: x.Date, ShippingNumber: x.ShippingNumber)) //<-- use GROUPBY for the Date and ShippingNumber
.Where(x => x.Count() > 1) //<-- use WHERE to filter those who only have 1 entry in a group consisting of Date+ShippingNumber
.Select(x => x.Key.ShippingNumber + "-> " + string.Join(",", x.Select(y => y.Id))) //<-- use SELECT to resolve the group to a string, there the Key is the combined Date + ShippingNumber and the Value is the flatList of that group
.ToList(); //<-- use TOLIST to make a List out of the IEnumerable

必须修复一些东西才能在 dotnetfiddle 上运行,但是你可以: https://dotnetfiddle.net/bKpUDz

关于c# - 如何根据日期合并两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54708967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com