Skip to content

Instantly share code, notes, and snippets.

@Implem
Created September 18, 2015 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Implem/2f7c94125546d405d43b to your computer and use it in GitHub Desktop.
Save Implem/2f7c94125546d405d43b to your computer and use it in GitHub Desktop.
c# リスト中に存在しない名前+連番の文字列を作成する ref: http://qiita.com/Implem/items/2e2f826e7f939f7547cf
using Implem.Libraries.Utilities;
using System;
using System.Collections.Generic;
namespace Implem.CodeDefiner
{
internal class Program
{
// 関数の使用例
static void Main(string[] args)
{
// 連番で 1, 2 が存在するリスト
var items = new List<string> { "設定1", "設定2" };
// リストに連番 3, 4, 5 を追加したい場合の使用例
items.Add(Unique.New(items, "設定"));
items.Add(Unique.New(items, "設定"));
items.Add(Unique.New(items, "設定"));
// 内容を出力
foreach(var item in items)
{
Console.WriteLine(item);
}
}
}
}
using System.Collections.Generic;
using System.Linq;
namespace Implem.Libraries.Utilities
{
public static class Unique
{
// リスト中に存在しない名前+連番の文字列を作成する関数
public static string New(IEnumerable<string> existing, string name, int start = 1)
{
var number = start;
while(existing.Any(o => o == name + number))
{
number++;
}
return name + number;
}
}
}
設定1
設定2
設定3
設定4
設定5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment