如何在C#中创建一个包含在另一个列表中的逗号分隔字符串?

huangapple go评论59阅读模式
英文:

How to make a comma separated string in list inside another list C#?

问题

Sure, here is the translated code:

我有一个对象列表(`Bookings`)。在其中,我有另一个对象列表(`Products`)。

我需要从这个方法中获取逗号分隔的产品ID

我已经使用了`foreach`循环,它正常工作。

private static string GetProductIDs(List<BookingModel>? Bookings)
{
    List<long> ProductIDS = new List<long>();

    foreach (var booking in Bookings)
    {
        var products = booking?.Products ;
        if (products != null)
        {
            foreach (var product in products)
            {
                if (product.ProductID != null)
                {
                    ProductIDS.Add((long)product.ProductID);
                }
            }
        }
    }
    return string.Join(",", ProductIDS.ToArray());
}

当我尝试以下代码时,它返回错误。你能帮我找到最好的方法吗?

var test = Bookings.SelectMany(c => c.Products.Where(p => p.ProductID != null)
    .Select(t => t.ProductID))
    .ToList();

return string.Join(",", test.ToArray());

错误:

如何在C#中创建一个包含在另一个列表中的逗号分隔字符串?

英文:

I have a list of objects (Bookings). Inside that I have a another list of objects (Products).

I need to get comma-separated product id's from this method

I have used for each and it's working fine

private static string GetProductIDs(List&lt;BookingModel&gt;? Bookings)
{

    List&lt;long&gt; ProductIDS = new List&lt;long&gt;();

    foreach (var booking in Bookings)
    {
        var products = booking?.Products ;
        if (products != null)
        {
            foreach (var product in products)
            {
                if (product.ProductID != null)
                {
                    ProductIDS.Add((long)product.ProductID);
                }

            }
        }   

    }
    return string.Join(&quot;,&quot;, ProductIDS.ToArray());

}

when I try the below code it's returning an error. could you please help me with the Best idea to do this?

var test = Bookings.SelectMany(c =&gt; c.Products.Where(p =&gt; p.ProductID != null)
    .Select(t =&gt; t.ProductID))
    .ToList();
        &#160;&#160;&#160;&#160;&#160;&#160;&#160;
return string.Join(&quot;,&quot;, test.ToArray());

Error:

如何在C#中创建一个包含在另一个列表中的逗号分隔字符串?

答案1

得分: 2

I would move the final string.Join() out of the method. Change the method design to return an IEnumerable<long>, and then use that result to produce the final comma-separated string.

Additionally, we can't see this for certain, but I suspect at least part of the error is you have a nullable long?, instead of a simple long for ProductID. Otherwise there would be no point in checking whether ProductID was null, as primitive values like long can never be null.

So the new method looks like this:

private static IEnumerable<long> GetProductIDs(IEnumerable<BookingModel>? Bookings)
{
    if (Bookings == null) return Enumerable.Empty<long>();

    return Bookings.Where(b => b.products is object).
               SelectMany(b => b.products.
                                 Where(p => p.ProductID.HasValue).
                                 Select(p => p.ProductID.Value)
                         );
}

And we can call it like this:

var result = string.Join(",", GetProductIDs(MyBookingList));

You might further want to take care to enforce a string format for the long=>string conversion that will not use additional comma separators between the segments of the numbers, which would throw off your CSV data. You get good behavior by default, but people can change it. You want to be sure it will continue to work regardless of what happens with the localization settings on the machine:

var result = string.Join(",", GetProductIDs(MyBookingList).Select(n => n.ToString("###")));
英文:

I would move the final string.Join() out of the method. Change the method design to return an IEnumerable&lt;long&gt;, and then use that result to produce the final comma-separated string.

Additionally, we can't see this for certain, but I suspect at least part of the error is you have a nullable long?, instead of a simple long for ProductID. Otherwise there would be no point in checking whether ProductID was null, as primitive values like long can never be null.

So the new method looks like this:

private static IEnumerable&lt;long&gt; GetProductIDs(IEnumerable&lt;BookingModel&gt;? Bookings)
{
    if (Bookings == null) return Enumerable.Empty&lt;long&gt;();

    return Bookings.Where(b =&gt; b.products is object).
               SelectMany(b =&gt; b.products.
                                 Where(p =&gt; p.ProductID.HasValue).
                                 Select(p =&gt; p.ProductID.Value)
                         );
}

And we can call it like this:

var result = string.Join(&quot;,&quot;, GetProductIDs(MyBookingList));

You might further want to take care to enforce a string format for the long=>string conversion that will not use additional comma separators between the segments of the numbers, which would throw off your CSV data. You get good behavior by default, but people can change it. You want to be sure it will continue to work regardless of what happens with the localization settings on the machine:

var result = string.Join(&quot;,&quot;, GetProductIDs(MyBookingList).Select(n =&gt; n.ToString(&quot;###&quot;));

答案2

得分: 0

以下是您提供的代码的中文翻译:

尝试

var test = Bookings.SelectMany(c => c.Products.Where(p => p.ProductID != null))
.Select(x => x.ProductID)
.ToArray();

英文:

Try

var test = Bookings.SelectMany(c =&gt; c.Products.Where(p =&gt; p.ProductID != null))
.Select(x =&gt; x.ProductID)
.ToArray();

huangapple
  • 本文由 发表于 2023年5月25日 21:39:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定