简体   繁体   English

C# 列表<string>包含特定字符串

[英]C# list<string> contains specific string

I have a list of strings (thing1-3, else1-3, other1-3), and I want to create a simplified list with just (thing, else, other).我有一个字符串列表 (thing1-3, else1-3, other1-3),我想创建一个仅包含 (thing, else, other) 的简化列表。 Seems straight forward (or at least this was with the Classic VB Dictionary .Exists function), but I'm stuck.看起来很简单(或者至少这是使用 Classic VB Dictionary .Exists 函数),但我被卡住了。 So I'm checking if the string startswith one of my simplified strings, then if the simplified list does not contain that string, add it.所以我正在检查字符串是否以我的简化字符串之一开头,然后如果简化列表不包含该字符串,则添加它。 But checking if the simplified list contains the string already is throwing me off.但是检查简化列表是否包含字符串已经让我失望了。

List<string> myList = new List<string>(new string[] { "thing1", "thing2", "thing3", "else1", "else2", "else3", "other1", "other2", "other3" });

List<string> myListSimplified = new List<string>();

foreach (string s in myList)
{
   if (s.StartsWith("thing"))
   {
      if (!myListSimplifed.Contains("thing")) { myListSimplifed.Add("thing"); }
   }

   if (s.StartsWith("else"))
   {
      if (!myListSimplifed.Contains("else")) { myListSimplifed.Add("else"); }
   }

   if (s.StartsWith("other"))
   {
      if (!myListSimplifed.Contains("other")) { myListSimplifed.Add("other"); }
   }
}

I would expect this mySimplifiedList to contain "thing", "else", "other", but it contains thing1-3, else1-2, other1-3.我希望这个 mySimplifiedList 包含“thing”、“else”、“other”,但它包含 thing1-3、else1-2、other1-3。

if (myListSimplified.Exists("thing")) { }

IntelliSense returns "cannot convert from 'string' to 'System.Predicate' IntelliSense 返回“无法从‘字符串’转换为‘System.Predicate’

ok.. so this:好的..所以这个:

if (!myListSimplified.Any(str => str.Contains("thing"))) { myListSimplified.Add("thing"); }

Or或者

if (!myListSimplified.Exists(str => str.Contains("thing"))) { myListSimplified.Add("thing"); }

None of these work.这些都不起作用。

Obviously I can create a method to iterate through the list and compare it to a string, but this functionality seems to be too fundamental to lists that MS left it out... Also seems silly to be passing lists around...显然,我可以创建一个方法来遍历列表并将其与字符串进行比较,但是此功能对于 MS 遗漏的列表来说似乎太基本了......传递列表似乎也很愚蠢......

private bool Exists(List<string> lList, string sCompare)
{
    bool bVal = false;

    foreach (string s in lList)
    {
        if (s == sCompare) { bVal = true; }
        break;
    }

    return bVal;
}

I'm not sure what your problem is:我不确定你的问题是什么:

First of all, it seems your first code snippet contains a typo: you have List<string> myListSimplified but then inside the foreach you reference myListSimplifed (missing 'i' after the 'f').首先,您的第一个代码片段似乎包含一个错字:您有List<string> myListSimplified但随后在foreach您引用了myListSimplifed (在“f”之后缺少“i”)。

If I correct that typo and run your code, then I get a list containing {"thing", "else", "other" } , which seems to be what you also expect.如果我更正了那个错字并运行了你的代码,那么我会得到一个包含{"thing", "else", "other" } ,这似乎也是你所期望的。

Besides the typo in myListSimplifed vs myListSimplified your code sample produces what you want it to do.除了 myListSimplifed 与 myListSimplified 中的拼写错误之外,您的代码示例会生成您想要它执行的操作。

Not what you ask for, but you can have the same effect with far fewer lines of code:不是您所要求的,但您可以使用更少的代码行获得相同的效果:

var myList = new List<string> {"thing1", "thing2", "thing3", "else1", "else2", "else3", "other1", "other2", "other3"};
var myListSimplified = myList.Select(s => new string(s.Where(char.IsLetter).ToArray())).Distinct();

Lists are generic data types.列表是通用数据类型。 They don't know what strings are, and so they're not provided out of the box with facilities to search for items that StartWith or Contain other strings.它们不知道什么是字符串,因此它们没有提供现成的工具来搜索StartWith包含其他字符串的项目。 This sort of operation doesn't make sense, generically speaking.一般来说,这种操作没有意义。 This is why you have operations like Any that take a lambda function to provide your own logic:这就是为什么你有像Any这样的操作使用 lambda 函数来提供你自己的逻辑:

if (myList.Any(str => str.StartsWith("thing")))
     mySimplifiedList.Add("thing");

I've tested this and it works fine.我已经测试过了,它工作正常。

Of course, if you have multiple strings you want to extract, you should probably make this more generic.当然,如果您有多个要提取的字符串,您可能应该使其更通用。 The simplest way is to extract the lines above to a method that receives the substring ("thing", in this case) as a parameter.最简单的方法是将上面的行提取到接收子字符串(在本例中为“thing”)作为参数的方法中。 A more generic approach (assuming it matches your data and logic) would be to go over all strings, strip all numerals from it, and store that.更通用的方法(假设它与您的数据和逻辑匹配)是遍历所有字符串,从中去除所有数字,然后存储它。 Assuming StripNumerals is a method that receives a string, it could look like this, with Distinct ensuring you have only one instance of each string.假设StripNumerals是一种接收字符串的方法,它可能看起来像这样, Distinct确保每个字符串只有一个实例。

var simplifiedList = myList.Select(StripNumerals).Distinct().ToList();

I have noticed your typo when putting the code in Visual Studio.将代码放入 Visual Studio 时,我注意到您的错字。 The result is correct, but your algorithm is far from being generic.结果是正确的,但您的算法远非通用。 What you can try:你可以尝试什么:

  1. var is useful to simplify declaration var有助于简化声明
  2. list initialization can be simplified列表初始化可以简化
  3. obtain a list by stripping all digits and perform a distinct on it通过剥离所有数字获得列表并对其执行不同的操作

    var myList = new List<string>() { "thing1", "thing2", "thing3", "else1", "else2", "else3", "other1", "other2", "other3" }; var listWithoutNumbers = myList.Select(s => { Regex rgx = new Regex("[0-9]"); return rgx.Replace(s, ""); }); var simplifiedList = listWithoutNumbers.Distinct();

Your original solution works, apart from the typo.除了错别字外,您的原始解决方案有效。 However, if you want more generic solution, you could use something like this但是,如果你想要更通用的解决方案,你可以使用这样的东西

List<string> myList = new List<string>(new string[] { "thing1", "thing2", "thing3", "else1", "else2", "else3", "other1", "other2", "other3" });

List<string> myListSimplified = myList.Select(s => new String(s.Where(Char.IsLetter).ToArray())).Distinct().ToList();

Don't forget to add不要忘记添加

using System.Linq;

if you will try this solution.如果你会尝试这个解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM