在c#中使用LINQ删除数组元素

本文关键字:LINQ 删除 数组元素 | 更新日期: 2023-09-27 17:50:50

如果数组元素不是从'%'开始的,可以从string[]数组中删除数组元素吗

string[] saBytesReceived = null; 
bDataReceived = new byte[bBytesToRead]; //byte[] array
networkStream.Read(bDataReceived, 0, bBytesToRead);
try
{
   if (ASCIIEncoding.ASCII.GetString(bDataReceived).Trim() != "")
   {
       saBytesReceived = ASCIIEncoding.ASCII.GetString(bDataReceived)
                         .Split(new string[] { "'0" }, StringSplitOptions.None);
      saBytesReceived = saBytesReceived.Select(s => s.Replace("?", "")).ToArray();     
      saBytesReceived = //Remove array elements in One single Line
    }
}

我不想使用任何循环…仅仅通过使用LINQ我们可以在单行中完成吗?

My Sample Array

65928346897326
34623462346346
%346346
%436534
32632463667364

结果数组应该是

%346346
%436534

在c#中使用LINQ删除数组元素

Linq是用于查询,而不是用于修改(删除项)。您可以获取以%:

开头的项。
saBytesReceived = saBytesReceived.Where(s => s.StartsWith("%")).ToArray();

这将创建一个包含你想要的元素的新数组:

%346346
%436534

是的,Linq内部会使用loop.


顺便说一句,你可以把你的代码重构成一个查询:

   string response = ASCIIEncoding.ASCII.GetString(bDataReceived);
   if (!String.IsNullOrWhiteSpace(response))
   {      
       saBytesReceived = response
              .Split(new string[] { "'0" }, StringSplitOptions.None)
              .Select(s => s.Replace("?", ""))
              .Where(s => s.StartsWith("%"))
              .ToArray();
   }