LINQ LIST转string[]

这是一个C#代码片段,用于从船舶列表中筛选出非空的SHIPID,并将其转换为字符串数组返回。方法首先通过LINQ查询获取SHIPID不为空的船舶列表,然后使用LINQ表达式进一步提取SHIPID,最后将结果数组返回。
        /// <summary>
        ///  返回船舶mmsID
        /// </summary>
        /// <returns></returns>
        public string[]  GetShipId()
        {
            string result = "";
            var list = this._service.GetShipList().Where(s=> s.SHIPID != "" && s.SHIPID != null).Select(s=>new { id = s.SHIPID}).ToList();
            var a = from o in list select o.id;
            //result = string.Join(",", a.ToArray());
            return a.ToArray();
        }

 

### 将C#中的List转换字符串 在C#中,有多种方法可以将`List<T>`对象转换字符串表示形式。以下是几种常见的方式: #### 使用 `string.Join` 最常用的方法之一是利用静态方法`string.Join`来连接列表中的所有元素。此方法接受分隔符以及要联接的集合作为参数。 ```csharp using System; using System.Collections.Generic; class Program { static void Main() { List<string> items = new List<string>() { "apple", "banana", "cherry" }; string result = string.Join(", ", items); Console.WriteLine(result); // 输出: apple, banana, cherry } } ``` 这种方法简单高效,并且能够很好地处理不同类型的数据[^1]。 #### 使用 LINQ 的 `Aggregate` 方法 对于更复杂的场景,比如自定义每个项之间的连接方式,则可以考虑使用LINQ提供的`Aggregate`函数来进行累加操作。 ```csharp using System; using System.Linq; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 }; string output = numbers.Aggregate(new System.Text.StringBuilder(), (sb, n) => sb.Append(n).Append(" * "), sb => sb.ToString().TrimEnd(' ', '*')); Console.WriteLine(output); // 输出: 1 * 2 * 3 * 4 * 5 } } ``` 这里通过传递初始值(`StringBuilder`)、聚合逻辑(追加当前数并加上乘号),最后再指定最终的结果转换规则去除多余的字符。 #### 调用 `ToString()` 和重写 如果希望整个列表作为一个整体具有特定格式化输出,还可以创建继承自`List<T>`的新类,并在其内部实现自己的`ToString()`方法。 ```csharp using System; using System.Collections.Generic; public class CustomStringList : List<string> { public override string ToString() { return $"Custom String List [{base.Count} items]"; } } class Program { static void Main() { var customItems = new CustomStringList(); customItems.Add("red"); customItems.Add("green"); Console.WriteLine(customItems.ToString()); // 输出: Custom String List [2 items] } } ``` 这种方式适用于需要对不同类型的列表提供统一外观的情况。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值