0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

csharp > 部分一致検索 > Dictionary <string, string>() > FirstOrDefault 使用

Last updated at Posted at 2016-08-22

関連 http://qiita.com/7of9/items/50557697949d3ddb30e7

上記のリンクにてDictionary <string, List<string>>()の検索を実施した。

しかしながら、自分が使いそうなのはDictionary <string, string>()の検索かもしれない。

実装してみた。

code v0.1

@ C# Online Snippet Compiler

using System;
using System.Collections.Generic;
using System.Linq;
			
public class Program
{
  public static string getElementWithLikeSearch(ref Dictionary<string,string>myDic, string searchKey)
  {
    var list = from name in myDic
      where name.Key.Contains(searchKey)
      select name;

    if (list.Count() == 0) {
      return "";
    }
        
    foreach(var element in list) {
      return element.Value;
    }
    return "";
  }
  
  public static void Main()
  {
    Dictionary <string, string> myDic = new Dictionary<string, string>();
    
    myDic.Add("HC-SR04", "Ultrasonic sensor...");
    myDic.Add("MAX232",  "The Max 220-Max249...");
    myDic.Add("MAX44242", "The MAX44242 provides...");
    
    string val;
	 	val = getElementWithLikeSearch(ref myDic, "MAX232");
    Console.WriteLine(":" + val);

	 	val = getElementWithLikeSearch(ref myDic, "MAX44242");
    Console.WriteLine(":" + val);
    
    val = getElementWithLikeSearch(ref myDic, "MAX");
    Console.WriteLine(":" + val);
  }
}
結果
:The Max 220-Max249...
:The MAX44242 provides...
:The Max 220-Max249...

備考

複数候補が見つかった時に1つ目を返す方法として以下としている。

    foreach(var element in list) {
      return element.Value;
    }

インデックス0のValueを返すようにする方法は未消化なのでforeachを使ってごまかしている。

改善code

@KeisukeKudo さんのコメントを参照ください。

@ C# Online Snippet Compiler

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?