-2

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我们可以在单行中完成吗?

我的样本数组

65928346897326
34623462346346
%346346
%436534
32632463667364

结果数组应该是

%346346
%436534
4

1 回答 1

7

Linq 用于查询,而不是用于修改(删除项目)。您可以获得以 % 开头的项目:

saBytesReceived = saBytesReceived.Where(s => s.StartsWith("%")).ToArray();

这将使用您想要的项目创建新数组:

%346346
%436534

是的,在内部 Linq 将使用循环。


顺便说一句,您可以将代码重构为单个查询:

   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();
   }
于 2013-01-04T13:52:37.940 回答