使用Linq查找与条目匹配的行

本文关键字:Linq 查找 使用 | 更新日期: 2023-09-27 18:20:28

我有以下格式的配置文件:

keydemo1,this is a demo version of the software
keyprod1,this is production version of the software

下面是基于键获取相关行的C#代码。所以,如果我通过了:GetEntryFromConfigFile ("config.ini", "keyprod1"),我期待着下面的整条线回来:

"keyprod1, this is production version of the software" 

但是,它不起作用。你能告诉我我做错了什么吗?

public static string GetEntryFromConfigFile(string fileName, string entryToFind)
{
    //var m = File.ReadLines(fileName).Where(l => l.IndexOf(entryToFind) != -1);
    //m = File.ReadLines(fileName).Where(l => l.ToLower().Contains(entryToFind.ToLower())).ToList();
    var m = File.ReadLines(fileName).Where(l => l.ToLower().IndexOf(entryToFind.ToLower()) > -1).ToList();
    //m returns 0 count;
    return m.ToString();        
}

使用Linq查找与条目匹配的行

使用StartsWith()IndexOf()不是一个好主意。如果文件中有两行以keydemo1keydemo11开头,该怎么办?

这就是我要做的:

public static string GetEntryFromConfigFile(string fileName, string entryToFind)
{
    return File.ReadLines(filename).FirstOrDefault(line => line.Split(',')[0].Equals(entryToFind, StringComparison.CurrentCultureIgnoreCase));
}

您可以尝试执行以下操作:

  var entry = File.ReadLines(fileName).FirstOrDefault(l => l.IndexOf(entryToFind,StringComparison.CurrentCultureIgnoreCase) >= 0)

这将检索一个条目。它将检查一行是否包含给定的字符串。它忽略了大小写和区域性设置。

试试这个

public static string GetEntryFromConfigFile(string fileName, string entryToFind)
{
    var m = File.ReadLines(fileName).Where(l => l.StartsWith(entryToFind, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); 
    return m;
}
public static string GetEntryFromConfigFile(string fileName, string entryToFind)
{
    return File.ReadLines(filename).FirstOrDefault(line => line.ToLower().Contains(entryToFind.ToLower()));
}