在C#中,是否有内联快捷方式来实例化只包含一个项目的List <T>.
我现在正在做:
new List<string>( new string[] { "title" } ))
Run Code Online (Sandbox Code Playgroud)
在任何地方使用此代码会降低可读性 我曾想过使用这样的实用方法:
public static List<T> SingleItemList<T>( T value )
{
return (new List<T>( new T[] { value } ));
}
Run Code Online (Sandbox Code Playgroud)
所以我能做到:
SingleItemList("title");
Run Code Online (Sandbox Code Playgroud)
有更短/更清洁的方式吗?
谢谢.
我有一个包含一堆可以多次出现的字符串的List.我想获取此列表并构建列表项的字典作为键和它们的出现次数作为值.
例:
List<string> stuff = new List<string>();
stuff.Add( "Peanut Butter" );
stuff.Add( "Jam" );
stuff.Add( "Food" );
stuff.Add( "Snacks" );
stuff.Add( "Philosophy" );
stuff.Add( "Peanut Butter" );
stuff.Add( "Jam" );
stuff.Add( "Food" );
Run Code Online (Sandbox Code Playgroud)
结果将是包含以下内容的字典:
"Peanut Butter", 2
"Jam", 2
"Food", 2
"Snacks", 1
"Philosophy", 1
Run Code Online (Sandbox Code Playgroud)
我有办法做到这一点,但似乎我没有利用C#3.0中的好东西
public Dictionary<string, int> CountStuff( IList<string> stuffList )
{
Dictionary<string, int> stuffCount = new Dictionary<string, int>();
foreach (string stuff in stuffList) {
//initialize or increment the count for this item
if (stuffCount.ContainsKey( stuff )) { …
Run Code Online (Sandbox Code Playgroud) 我已经将textarea元素的输入保存到MySQL中的TEXT列.我正在使用PHP从数据库中提取数据,并希望在显示用户输入的空格(例如多个空格和换行符)时将其显示在ap元素中.我试过一个pre标签,但它不遵守包含div元素中设置的宽度.除了创建PHP函数以将空格转换为新行和br标签之外,我有哪些选择?我更喜欢干净的HTML/CSS解决方案,但欢迎任何输入!谢谢!
鉴于以下代码,为什么在"Main"的第一行之后调用"Outer"的静态构造函数?
namespace StaticTester
{
class Program
{
static void Main( string[] args )
{
Outer.Inner.Go();
Console.WriteLine();
Outer.Go();
Console.ReadLine();
}
}
public static partial class Outer
{
static Outer()
{
Console.Write( "In Outer's static constructor\n" );
}
public static void Go()
{
Console.Write( "Outer Go\n" );
}
public static class Inner
{
static Inner()
{
Console.Write( "In Inner's static constructor\n" );
}
public static void Go()
{
Console.Write( "Inner Go\n" );
}
}
}
}
Run Code Online (Sandbox Code Playgroud)