基于显示的代码..我是否正在编写正确的编码,如果我想比较正在流的数据?基本上从部分开始
while(serialPort1.IsOpen)
例如,收到的第一个数据字符串是 T 12 29.5 ,然后下一个字符串是 T 12 29.5 ,然后是 T 20 24.5 ,然后是......基本上无法预测接下来会收到什么。
我想编程能够检测/计算中间值的外观数量......比如......
====================
[编号] | [重复次数]
12 | 2
===================但是当收到另一个不同的号码时,
[数字] | [反复]
20 | 1
===================只要收到不同的号码,该号码的计数器就会被覆盖和重置。
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string time = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff");
RxString = serialPort1.ReadLine();
string[] split = RxString.Split('.');
string dp = split[1];
Char c = dp[0];
split[1] = c.ToString();
RxString = split[0] + "." + split[1];
while (serialPort1.IsOpen)
{
string[] number = RxString.Split(' ');
string unit = number[1];
int count = 1;
for(int i = 1; i < unit.Count(); i++)
{
if(unit[i-1] == unit[i])
count++;
else
count = 1;
if(count == 4)
{
//execute some parameters
}
}
}
this.Invoke(new EventHandler(DisplayText));
StreamWriter MyStreamWriter = new StreamWriter(@"C:\Users\acer\Documents\Data3.txt", true);
MyStreamWriter.Write(time + " " + RxString + "\r\n");
MyStreamWriter.Flush();
MyStreamWriter.Close();
}
EDIT V2
为什么不会将记录数据只计数为1?
string[] number = RxString.Split(' '); //split RxString by ' '
string unit = number[1]; //unit = unit no.
int count = 1;
for (int i = 1; i < unit.Count(); i++)
{
if (unit[i - 1] == unit[i])
count++;
else
{
count = 1;
StreamWriter MyStreamWriter = new StreamWriter(@"C:\Users\acer\Documents\Data3.txt", true); //True tell SW to append to file instead of overwriting
MyStreamWriter.Write(time + " " + RxString + "\r\n"); //Write time + string
MyStreamWriter.Flush();
MyStreamWriter.Close();
}
答案 0 :(得分:1)
您应该使用字典来存储每个元素及其自己的计数:
var dict = new Dictionary<string, int?>();
while (serialPort1.IsOpen)
{
string[] number = RxString.Split(' ');
string unit = number[1];
if (dict.ContainsKey(unit))
{
if (dict[unit].HasValue)
{
dict[unit]++;
if (dict[unit] == 4)
{
// execute some parameters
dict[unit] = null;
}
}
}
else
{
dict.Add(unit, 1);
}
}
答案 1 :(得分:0)
我会为此创建一个特殊的结构:
struct DataInfo
{
public string Number { get; set; }
public int Counter { get; set; }
... Other data you require to work with
}
并使用List<DataInfo>
或Dictionary<string, DataInfo>
来存储值;