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

时间:2015-11-03 19:41:05

标签: c# linq

我的配置文件格式如下:

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();        
}

4 个答案:

答案 0 :(得分:2)

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

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

这将检索一个条目。它将检查一行是否包含给定的字符串。它忽略了套管和文化设置。

答案 1 :(得分:2)

使用StartsWith()IndexOf()不是一个好主意。如果您的文件中有两行以keydemo1keydemo11开头?

,该怎么办?

这就是我要做的事情:

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

答案 2 :(得分:1)

试试这个

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

答案 3 :(得分:1)

public static string GetEntryFromConfigFile(string fileName, string entryToFind)
{
    return File.ReadLines(filename).FirstOrDefault(line => line.ToLower().Contains(entryToFind.ToLower()));
}