コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】文字列の中に重複する文字が存在する場合 true を返す拡張メソッド

C#

ソースコード private static bool HasDuplicateCharacters( string self ) { for ( var i = 0; i < self.Length - 1; i++ ) { for ( var j = i + 1; j < self.Length; j++ ) { if ( self[ i ] == self[ j ] ) { return true; } } } return false; } 使用例 …

【C#】配列やリストの中に重複する要素が存在する場合 true を返す拡張メソッド

C#

ソースコード private static bool HasDuplicateElements<T>( this IReadOnlyList<T> self ) { for ( var i = 0; i < self.Count - 1; i++ ) { for ( var j = i + 1; j < self.Count; j++ ) { if ( self[ i ].Equals( self[ j ] ) ) { return true; } } } return f</t></t>…

【C#】float 型がほぼ整数なら true を返す拡張メソッド

C#

ソースコード public static bool IsApproximatelyInteger( this float value, float tolerance ) { return Mathf.Abs( Mathf.Round( value ) - value ) <= tolerance; }

【C#】List から複数の要素を Remove する拡張メソッド

C#

ソースコード public static void Remove<T>( this List<T> self, IEnumerable<T> collection ) { foreach ( var item in collection ) { self.Remove( item ); } }</t></t></t>

【C#】配列やリストから重複する要素を取得する拡張メソッド

C#

ソースコード public static T[] FindDuplicatedElements<T>( this IReadOnlyList<T> self ) { return self .GroupBy( x => x ) .Where( x => 2 <= x.Count() ) .Select( x => x.Key ) .ToArray() ; }</t></t>

【C#】小数点以下を取得する方法

C#

余りを使用する方法 var number = 3.14f; var decimalPart = number % 1; if (decimalPart != 0) { // 浮動小数点以下が存在する場合の処理 } 文字列変換を使用する方法 var number = 3.14f; var numberString = number.ToString(); if (numberString.Contai…

【C#】起動している Microsoft PowerPoint のプロセスを終了する方法

C#

ソースコード foreach ( var process in Process.GetProcessesByName( "POWERPNT" ) ) { process.Kill(); }

【C#】文字列を回転する関数

C#

概要 123 456 789 上記の値を持つ string を 147 258 369 このように変換する関数 private static string TransposeString( string input ) { var lines = input.Split( '\n' ); var rowCount = lines.Length; var columnCount = lines[ 0 ].Length; var mat…

【C#】null 許容の SequenceEqual

C#

ソースコード public static bool SequenceEqualAllowedNull<TSource> ( this IEnumerable<TSource> self, IEnumerable<TSource> second ) { return self switch { null when second == null => true, null => false, _ => second != null && self.SequenceEqual( second ) }; } 使用例 </tsource></tsource></tsource>…

【Unity】文字列が変数名に使用できるか確認する方法

概要 using System.CodeDom.Compiler; using UnityEditor; using UnityEngine; public static class Example { [MenuItem( "Tools/Hoge" )] private static void Hoge() { var provider = CodeDomProvider.CreateProvider( "C#" ); Debug.Log( provider.IsVa…

【C#】ラムダ式で入力参照渡しの引数を受け取る方法

C#

概要 private delegate void Delegate( in Vector2 position ); private void Run( Delegate deletgate ) { deletgate += ( in Vector2 position ) => Debug.Log( position ); } 引数が入力参照渡しであることを明示的に記述する必要がある

【C#】最初に見つかった文字列だけ置換する string.Replace

ソースコード public static string ReplaceFirst ( this string self, string oldValue, string newValue ) { var startIndex = self.IndexOf( oldValue ); if ( startIndex == -1 ) return self; return self .Remove( startIndex, oldValue.Length ) .Ins…

【C#】Code Cracker の CC0022 は C# 8.0 以降の using 変数宣言に対応していない

C#

参考サイト様

【C#】float の値が 0 かどうかを確認する拡張メソッド

ソースコード using System; public static class FloatExtensions { public static bool IsZero( this float self ) { return self.IsZero( float.Epsilon ); } public static bool IsZero( this float self, float epsilon ) { return Math.Abs( self ) < …

【C#】TaskCompletionSource と CancellationToken を組み合わせて使う方法

C#

概要 using System; using System.Threading; using System.Threading.Tasks; using UnityEngine; public sealed class Example : MonoBehaviour { private readonly CancellationTokenSource m_cancellationTokenSource = new(); private async void Start(…

【C#】配列やリストの要素がすべて同じかどうか確認する方法

C#

概要 using System.Linq; using UnityEngine; public class Example : MonoBehaviour { private void Awake() { var list1 = new[] { 1, 2, 3 }; var list2 = new[] { 1, 1, 1 }; Debug.Log( list1.Distinct().Count() == 1 ); // False Debug.Log( list2.Di…

【C#】継承しているすべての基底クラスと実装しているすべてのインターフェイスの Type を返す拡張メソッド

C#

概要 /// <summary> /// 継承しているすべての基底クラスと実装しているすべてのインターフェイスの Type を返します /// </summary> public static IEnumerable<Type> GetParentTypes( this Type self ) { if ( self == null ) yield break; foreach ( var x in self.GetInterfaces()</type>…

【C#】基底クラスを継承しているもしくはインターフェイスを実装している場合 true を返す拡張メソッド

C#

概要 /// <summary> /// 指定された基底クラスを継承しているもしくはインターフェイスを実装している場合 true を返します /// </summary> public static bool IsInherits( this Type self, Type baseOrInterfaceType ) { if ( self == null ) return false; if ( baseOrInterf…

【C#】MethodInfo が拡張メソッドなら true を返す拡張メソッド

C#

ソースコード using System.Reflection; using System.Runtime.CompilerServices; namespace Kogane { public static class MethodInfoExtensionMethods { public static bool IsExtensionMethod( this MethodInfo self ) { return self.IsDefined( typeof( …

【C#】Type が nullable なら true を返す拡張メソッド

C#

ソースコード public static class TypeExtensionMethods { public static bool IsNullable( this Type self ) { return Nullable.GetUnderlyingType( self ) != null; } }

【C#】NPOI でどんなセルの値も文字列で取得できる拡張メソッド

拡張メソッド using NPOI.SS.UserModel; namespace Kogane { public static class ICellExtensionMethods { public static string GetValue( this ICell self ) { if ( self == null ) return string.Empty; return self.CellType switch { CellType.Numeric…

【C#】CancellationToken.None == default は True

C#

概要 using System.Threading; using UnityEngine; public class Example : MonoBehaviour { private void Awake() { Debug.Log( CancellationToken.None == default ); // True } }

【C#】TryElementAt 拡張メソッド

C#

ソースコード using System; using System.Collections.Generic; namespace Kogane { // ReSharper disable once InconsistentNaming public static class IEnumerableExtensionMethods { public static bool TryElementAt<TSource> ( this IEnumerable<TSource> source, int i</tsource></tsource>…

【C#】組み込み型の名前を「Int32」ではなく「int」という形式で取得する方法

C#

ソースコード using System; namespace Kogane { public static class TypeUtils { public static string GetCSharpTypeKeyword( Type type ) { return GetCSharpTypeKeyword( type.Name ); } // https://stackoverflow.com/questions/56352299/gettype-retu…

【C#】ジェネリック型の名前を「Dictionary`2」ではなく「Dictionary<int, string>」という形式で取得する方法

C#

ソースコード using System; using System.Linq; namespace Kogane { public static class TypeUtils { // https://stackoverflow.com/questions/1533115/get-generictype-name-in-good-format-using-reflection-on-c-sharp public static string GetPrettyN…

【C#】文字が英数字かどうかを確認する拡張メソッド

C#

ソースコード namespace Kogane { public static class CharExtensionMethods { public static bool IsAlphanumeric( this char self ) { return char.IsLetterOrDigit( self ); } } } 使用例 Debug.Log( '0'.IsAlphanumeric() ); // True Debug.Log( 'A'.Is…

【C#】文字列が英数字のみで構成されているかどうかを確認する拡張メソッド

C#

ソースコード namespace Kogane { public static class StringExtensionMethods { public static bool IsAlphanumeric( this string self ) { for ( var i = 0; i < self.Length; i++ ) { var x = self[ i ]; if ( !char.IsLetterOrDigit( x ) ) { return fa…

【Unity】Java の Stream API の Peek のような機能を LINQ で使えるようにする拡張メソッド

ソースコード using System; using System.Collections.Generic; using JetBrains.Annotations; namespace Kogane { public static class IEnumerablePeekExtensionMethods { public static IEnumerable<T> Peek<T> ( [NotNull] this IEnumerable<T> source, [NotNull</t></t></t>…

【C#】文字が半角英数字かどうかを判定する方法

C#

概要 var isAlphanumeric = char.IsLetterOrDigit( 'A' ); // True char.IsLetterOrDigit を使うと判定できる 0 ~ 9、A ~ Z、a ~ z は True になる 記号や半角スペースは False になる 使用例 // 0 ~ 9、A ~ Z、a ~ z は True になる var isAlphanumeric = "…

【Unity】LINQ で抽出した要素をログ出力して確認できるようにする拡張メソッド

ソースコード using System; using System.Collections.Generic; using JetBrains.Annotations; using UnityEngine; namespace Kogane { public static class IEnumerableLogExtensionMethods { public delegate void LogDelegate( object item ); public st…