我有以下函数在文本中搜索IP并将其添加到DataGrid。
try
{
string source = e.Result;
Regex re = new Regex(@"(\d+\.\d+\.\d+\.\d+):1400");
MatchCollection mc = re.Matches(source);
if (mc.Count > 0)
{
foreach (Match matches in mc)
{
int index = dataGridAllSonos.Columns.ToList().FindIndex(c => c.Header == matches.Groups[1].Value);
Console.WriteLine(index);
var data = new sonosDevice
{
sonosIP = matches.Groups[1].Value,
sonosName = "XX",
sonosRoom = "XX"
};
dataGridAllSonos.Items.Add(data);
}
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
string err = ex.InnerException.Message;
Console.WriteLine(err);
}
}
行int index = dataGridAllSonos.Columns.ToList().FindIndex(c => c.Header == matches.Groups[1].Value);
用于检查当前找到的IP(第一列)是否已存在于DataGrid中。不应该添加它。
不幸的是,它总是返回-1
所以找不到,我怎样才能检查IP是否重复?
sonosDevice Class
public class sonosDevice
{
public string sonosIP { get; set; }
public string sonosName { get; set; }
public string sonosRoom { get; set; }
}
答案 0 :(得分:0)
试试这个:
bool found = dataGridAllSonos.Items.OfType<string>().Any(i => i == matches.Groups[1].Value);