本文整理汇总了C#中Dictionary类的典型用法代码示例。如果您正苦于以下问题:C# Dictionary类的具体用法?C# Dictionary怎么用?C# Dictionary使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Dictionary类属于命名空间,在下文中一共展示了Dictionary类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ServerConsole
void ServerConsole()
{
var stringMatch = new Regex(@"\""(?<text>.*?)\""|(?<text>\w+)", RegexOptions.Compiled);
var commands = new Dictionary<string, Action<string[]>>()
{
["shutdown"] = this.Shutdown,
["quit"] = this.Shutdown,
["save"] = this.Save,
};
while(true)
{
string line = Console.ReadLine();
var matches = stringMatch.Matches(line);
var command = matches.Cast<Match>().Take(1).Select(x => x.Groups["text"].Value).First().ToLower();
var args = matches.Cast<Match>().Skip(1).Select(x => x.Groups["text"].Value).ToArray();
if(commands.ContainsKey(command))
{
commands[command](args);
}
else
{
Console.WriteLine("Command ´{0}´ not found.", command);
}
}
}
示例2: Main
public static void Main(string[] args)
{
Dictionary<string, Action> options = new Dictionary<string, Action>()
{
{ "interfaces", PrintNetworkInterfaces },
{ "interfaceproperties", PrintNetworkInterfaceProperties },
{ "interfacestatistics", PrintNetworkInterfaceStatistics },
{ "ipv4", PrintIpv4Statistics },
{ "ipv6", PrintIpv6Statistics },
{ "icmp4", PrintIcmp4Statistics },
{ "icmp6", PrintIcmp6Statistics },
{ "udp4", PrintUdp4Statistics },
{ "udp6", PrintUdp6Statistics },
{ "tcp4", PrintTcp4Statistics },
{ "tcp6", PrintTcp6Statistics },
{ "connections", PrintSocketConnections },
{ "networkchange", NetworkChangeTest },
{ "ipglobal", PrintIPGlobals }
};
string selection = (args?.Length >= 1) ? args[0] : null;
if (selection == null || !options.Keys.Contains(selection))
{
Console.WriteLine("Options: " + Environment.NewLine + string.Join(Environment.NewLine, options.Keys.Select(s => $"* {s}")));
}
else
{
options[selection]();
}
}
示例3: InvokeOutputMethod
public string InvokeOutputMethod(string method, string param)
{
Dictionary<string, Func<string>> dictMethod = new Dictionary<string, Func<string>>() {
{"GetCellText",()=>GetCellText(Convert.ToInt32(param.Split('|')[0]),Convert.ToInt32(param.Split('|')[1]))}
};
return dictMethod[method]();
}
示例4: InvokeOutputMethod
public string InvokeOutputMethod(string method, string param)
{
Dictionary<string, Func<string>> dictMethod = new Dictionary<string, Func<string>>() {
{"IsChecked",()=>IsChecked()?"1":"0"}
};
return dictMethod[method]();
}
示例5: Configuration
public void Configuration(IAppBuilder app)
{
app.Use(async (ctx, next) =>
{
var actions = new Dictionary<string, Func<IAsyncDocumentSession, Task>>
{
{"GET", async session =>
{
var url = await session.LoadAsync<Url>(ctx.Request.Path.Value.Substring(1));
if (url != null)
{
ctx.Response.StatusCode = (int) HttpStatusCode.MovedPermanently;
ctx.Response.Headers["Location"] = url.Location;
}
else ctx.Response.StatusCode = (int)HttpStatusCode.NotFound;
}},
{"POST", async session =>
{
var random = new Random();
var hash = string.Join("", Enumerable.Range(0, 7).Select(_ => Chars[random.Next(Chars.Length)]));
await session.StoreAsync(new Url {Id = hash, Location = ctx.Request.Query["path"]});
await session.SaveChangesAsync();
ctx.Response.StatusCode = (int)HttpStatusCode.Created;
await ctx.Response.WriteAsync(hash);
}}
};
using (var session = DocumentStore.OpenAsyncSession())
await actions[ctx.Request.Method](session);
});
}
示例6: InvokeOutputMethod
public string InvokeOutputMethod(string method, string param)
{
Dictionary<string, Func<string>> dictMethod = new Dictionary<string, Func<string>>() {
{"GetText",()=>GetText()}
};
return dictMethod[method]();
}
示例7: Init
/// <summary>
/// Initialize the QvFacebookConnection.
/// </summary>
public override void Init()
{
QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Notice, "Init()");
// Log in to facebook
LoginToFacebook();
MTables = new List<QvxTable>();
// Create all supported tables
var tableDictionary = new Dictionary<FacebookMetadataTag, Func<FacebookMetadataTag, QvxTable>>
{
{ FacebookMetadataTag.friends, x => CreatePersonsTable(x) },
{ FacebookMetadataTag.family, x => CreatePersonsTable(x) },
{ FacebookMetadataTag.movies, x => CreateEntertainmentTable(x) },
{ FacebookMetadataTag.television, x => CreateEntertainmentTable(x) },
{ FacebookMetadataTag.likes, x => CreateEntertainmentTable(x) },
{ FacebookMetadataTag.books, x => CreateEntertainmentTable(x) },
{ FacebookMetadataTag.music, x => CreateEntertainmentTable(x) },
{ FacebookMetadataTag.games, x => CreateEntertainmentTable(x) },
};
if (tableDictionary.Keys.Count != Enum.GetNames(typeof(FacebookMetadataTag)).Length)
{
QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Warning, "Init() - Mismatch between the number of supported metadata tags and tables");
}
foreach (var key in tableDictionary.Keys)
{
MTables.Add(tableDictionary[key](key));
}
}
示例8: ClientHandler
public static void ClientHandler(TcpClient client) {
var d = new Dictionary<string, ProcessCommand>() {
{ "cat", CatFile },
{ "clx", CalcClx },
{ "erf", CalcErf },
{ "sz", FileSize },
{ "info", GetInfo }
};
while (client.Connected) {
using (var streamReader = new StreamReader(client.GetStream()))
using (var streamWriter = new StreamWriter(client.GetStream())) {
var cmd = streamReader.ReadLine().Split(" ".ToCharArray(), 2);
try {
d[cmd[0]](cmd[1], streamWriter);
}
catch {
streamWriter.WriteLine("Error :(");
}
streamWriter.Flush();
}
}
client.Close();
}
示例9: FromFile
public static void FromFile(string csvPath, string jsonPath, Dictionary<string, string> propertyMapper, Dictionary<string, Func<string, dynamic>> customValueMappers, Func<Dictionary<string, dynamic>, bool> excludeEntryPredicate)
{
string[] lines = File.ReadAllLines(csvPath);
if (lines.Length == 0)
{
return;
}
string[] properties = ParseProperties(lines[0], propertyMapper);
List<Dictionary<string, dynamic>> jsonPayload = new List<Dictionary<string, dynamic>>(lines.Length - 1);
foreach (string line in lines.Skip(1))
{
Dictionary<string, dynamic> entry = new Dictionary<string, dynamic>();
int propertyIndex = 0;
foreach (string value in CleanCsvEntry(SplitCsvLine(line)))
{
string property = properties[propertyIndex];
entry[property] = customValueMappers.ContainsKey(property) ? customValueMappers[property](value) : ParseValue(value);
propertyIndex++;
}
if (excludeEntryPredicate != null && excludeEntryPredicate(entry))
{
continue;
}
jsonPayload.Add(entry);
}
File.WriteAllText(jsonPath, JsonConvert.SerializeObject(jsonPayload, Formatting.Indented));
}
示例10: FireStateEvent
public void FireStateEvent(Dictionary<int, StateListenerEvent> vDic,
int vStateType,
object vObj)
{
if(vDic.ContainsKey(vStateType))
vDic[vStateType](vObj);
}
示例11: Run
public void Run(IBus bus, TextWriter w)
{
_c.Add(bus.Subscribe<MessageA>(OnMessageA));
_c.Add(bus.Subscribe<MessageB>(OnMessageB));
_c.Add(bus.Subscribe<MessageC>(OnMessageC));
var r = new Random();
var dict = new Dictionary<int, Func<object>>
{
{0, () => new MessageA()},
{1, () => new MessageB()},
{2, () => new MessageC()},
};
int count = 0;
var sw = Stopwatch.StartNew();
while (count < 100000)
{
bus.Publish(dict[r.Next(0, 3)]());
count++;
}
w.WriteLine("Through {0}", sw.ElapsedMilliseconds);
while (_aCount != MessageA.Count && _bCount != MessageB.Count && _cCount != MessageC.Count)
{
WriteInfo(w);
Thread.Sleep(1000);
}
WriteInfo(w);
}
示例12: Run
public void Run(IBus bus, TextWriter w)
{
c.Add(bus.Subscribe<MessageA>(onMessageA));
c.Add(bus.Subscribe<MessageB>(onMessageB));
c.Add(bus.Subscribe<MessageC>(onMessageC));
var r = new Random();
var dict = new Dictionary<int, Func<object>>
{
{0, () => new MessageA()},
{1, () => new MessageB()},
{2, () => new MessageC()},
};
int count = 0;
var sw = Stopwatch.StartNew();
while (count < 100000)
{
bus.Publish(dict[r.Next(0, 3)]());
count++;
}
w.WriteLine("Through {0}", sw.ElapsedMilliseconds);
count = 0;
while (count < 10)
{
w.WriteLine("From MsgA:{0}({1}), B:{2}({3}), C:{4}({5})", aCount, MessageA.Count, bCount,
MessageB.Count, cCount, MessageC.Count);
Thread.Sleep(1000);
count++;
}
}
示例13: OnCreate
//private void PrepareLiveDataVector()
//{
// if ((model == (StaticString.beforeBlank + Database.GetText("QM125T-8H", "QingQi"))) ||
// (model == (StaticString.beforeBlank + Database.GetText("QM250GY", "QingQi"))) ||
// (model == (StaticString.beforeBlank + Database.GetText("QM250T", "QingQi"))))
// {
// Manager.LiveDataVector = Database.GetLiveData("Synerject");
// }
// else if ((model == (StaticString.beforeBlank + Database.GetText("QM200GY-F", "QingQi"))) ||
// (model == (StaticString.beforeBlank + Database.GetText("QM200-3D", "QingQi"))) ||
// (model == (StaticString.beforeBlank + Database.GetText("QM200J-3L", "QingQi"))))
// {
// Manager.LiveDataVector = Database.GetLiveData("Mikuni");
// }
// else
// {
// Manager.LiveDataVector = Database.GetLiveData("Visteon");
// }
//}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create your application here
Window.SetFlags(WindowManagerFlags.KeepScreenOn, WindowManagerFlags.KeepScreenOn);
List<string> arrays = new List<string>();
arrays.Add(StaticString.beforeBlank + Database.GetText("Dynamic Data Stream", "System"));
arrays.Add(StaticString.beforeBlank + Database.GetText("Static Data Stream", "System"));
funcs = new Dictionary<string, Func>();
funcs.Add(Database.GetText("Dynamic Data Stream", "System"), () =>
{
//PrepareLiveDataVector();
Intent intent = new Intent(this, typeof(DataStreamActivity));
intent.PutExtra("Model", model);
StartActivity(intent);
});
funcs.Add(Database.GetText("Static Data Stream", "System"), () =>
{
//PrepareLiveDataVector();
Intent intent = new Intent(this, typeof(StaticDataStreamActivity));
intent.PutExtra("Model", model);
StartActivity(intent);
});
ListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, arrays);
ListView.ItemClick += (sender, e) =>
{
string test = ((TextView)e.View).Text;
funcs[test.TrimStart(' ')]();
};
}
示例14: Create
public static RuleRewriter Create(Type type, ISettings settings, Func<SemanticModel> semanticModel)
{
// A dictionary of all recognised constructor parameters.
Dictionary<Type, Func<object>> parameterTypes = new Dictionary<Type, Func<object>>
{
{ typeof(ISettings), () => settings },
{ typeof(SemanticModel), semanticModel },
};
// Get a list of the type's constructors together with the constructor parameters types,
// ordered by number of parameters descending.
var ctors = (from c in type.GetConstructors()
select new
{
ConstructorInfo = c,
Parameters = c.GetParameters()
}).OrderByDescending(x => x.Parameters.Length).ToArray();
// Get the first constructor in which we recognise all parameter types.
var ctor = ctors.FirstOrDefault(x => x.Parameters.All(p => parameterTypes.Keys.Contains(p.ParameterType)));
object[] parameters = ctor.Parameters.Select(x => parameterTypes[x.ParameterType]()).ToArray();
return (RuleRewriter)ctor.ConstructorInfo.Invoke(parameters);
}
示例15: AutoRedirectTests
public AutoRedirectTests()
{
var responders = new Dictionary<string, Action<IOwinContext>>
{
{ "/redirect-absolute-302", context =>
{
context.Response.StatusCode = 302;
context.Response.ReasonPhrase = "Found";
context.Response.Headers.Add("Location", new [] { "http://localhost/redirect" });
}
},
{ "/redirect-relative", context =>
{
context.Response.StatusCode = 302;
context.Response.ReasonPhrase = "Found";
context.Response.Headers.Add("Location", new [] { "redirect" });
}
},
{ "/redirect-absolute-301", context =>
{
context.Response.StatusCode = 301;
context.Response.ReasonPhrase = "Moved Permanently";
context.Response.Headers.Add("Location", new [] { "http://localhost/redirect" });
}
},
{ "/redirect-absolute-303", context =>
{
context.Response.StatusCode = 303;
context.Response.ReasonPhrase = "See Other";
context.Response.Headers.Add("Location", new [] { "http://localhost/redirect" });
}
},
{ "/redirect-absolute-307", context =>
{
context.Response.StatusCode = 307;
context.Response.ReasonPhrase = "Temporary Redirect";
context.Response.Headers.Add("Location", new [] { "http://localhost/redirect" });
}
},
{ "/redirect-loop", context =>
{
context.Response.StatusCode = 302;
context.Response.ReasonPhrase = "Found";
context.Response.Headers.Add("Location", new[] { "http://localhost/redirect-loop" });
}
},
{ "/redirect", context => context.Response.StatusCode = 200 }
};
AppFunc appFunc = env =>
{
var context = new OwinContext(env);
responders[context.Request.Path.Value](context);
return Task.FromResult((object)null);
};
_handler = new OwinHttpMessageHandler(appFunc)
{
AllowAutoRedirect = true
};
}