本文整理汇总了C#中Dictionary.ToDictionary方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.ToDictionary方法的具体用法?C# Dictionary.ToDictionary怎么用?C# Dictionary.ToDictionary使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Dictionary
的用法示例。
在下文中一共展示了Dictionary.ToDictionary方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ParseInput
static void ParseInput()
{
n = int.Parse(Console.ReadLine());
stationsInfo = Regex.Matches(
("0 --> " + Console.ReadLine()).Replace(" --> ", "►"),
"([^►]+)►([^►]+)"
).Cast<Match>()
.Select(match =>
new KeyValuePair<string, int>(
match.Groups[2].Value,
int.Parse(match.Groups[1].Value)
)
).ToArray();
int id = 0;
stationsByName = stationsInfo.ToDictionary(
info => info.Key,
info => id++
);
stationsByIndex = stationsByName.ToDictionary(
kvp => kvp.Value,
kvp => kvp.Key
);
var separator = new string[] { " | " };
camerasInfo = Enumerable.Range(0, int.Parse(Console.ReadLine()))
.Select(_ => Console.ReadLine())
.Select(line => line.Split(separator, StringSplitOptions.None))
.Select(match =>
new Tuple<DateTime, int, int, int, char>(
DateTime.ParseExact(match[0], DateFormat, CultureInfo.InvariantCulture),
stationsByName[match[1]],
int.Parse(match[2]),
int.Parse(match[3]),
match[4][0]
)
).ToArray();
trainCapacity = int.Parse(Console.ReadLine());
#if DEBUG
//Console.WriteLine("# INPUT");
//Console.WriteLine(string.Join(Environment.NewLine, stationsInfo));
//Console.WriteLine();
//Console.WriteLine(string.Join(Environment.NewLine, camerasInfo));
//Console.WriteLine();
//Console.WriteLine(trainCapacity);
//Console.WriteLine();
#endif
}
示例2: SomeFunction
public static void SomeFunction()
{
Dictionary<int, int> dict = new Dictionary<int, int>();
dict.Add(4, 3);
Console.WriteLine(dict[4]);
Console.WriteLine(dict.ContainsKey(8));
dict.Remove(4);
foreach(int key in dict.Keys)
Console.WriteLine(key);
foreach(int val in dict.Values)
Console.WriteLine(val);
foreach(var kv in dict)
Console.WriteLine(kv.Key + " " + kv.Value);
var dict2 = dict.ToDictionary(o => o.Key, o => o.Value);
var vals = dict.Values;
HashSet<int> hash = new HashSet<int>();
hash.Add(999);
Console.WriteLine(hash.Contains(999));
hash.Remove(999);
Console.WriteLine(hash.Contains(999));
foreach(int hashItem in hash)
Console.WriteLine(hashItem);
var z = hash.Select(o => 3).ToArray();
var g = hash.GroupBy(o => o).Select(o => o.Count()).Min();
}
示例3: HistoryTickerStream
public HistoryTickerStream(Dictionary<string, List<CandleDataBidAsk>> quotes)
{
this.quotes = quotes;
if (quotes.Count == 0) return;
currentIndex = quotes.ToDictionary(q => q.Key, q => 0);
timeNow = quotes.Select(q => q.Value.Count == 0 ? DateTime.MaxValue : q.Value[0].timeClose).Min();
}
示例4: ConvertFrom
public static Dictionary<string, List<SmallRNASequence>> ConvertFrom(List<ChromosomeCountSlimItem> items)
{
var result = new Dictionary<string, Dictionary<string, SmallRNASequence>>();
foreach (var c in items)
{
foreach (var q in c.Queries)
{
Dictionary<string, SmallRNASequence> seqList;
if (!result.TryGetValue(q.Sample, out seqList))
{
seqList = new Dictionary<string, SmallRNASequence>();
result[q.Sample] = seqList;
}
if (!seqList.ContainsKey(q.Sequence))
{
seqList[q.Sequence] = new SmallRNASequence()
{
Sample = q.Sample,
Sequence = q.Sequence,
Count = q.QueryCount
};
}
}
}
return result.ToDictionary(l => l.Key, l => l.Value.Values.ToList());
}
示例5: GenerateTextWithKey
public async Task<Dictionary<string, string>> GenerateTextWithKey(CancellationToken cancellationToken)
{
var generatedTaskObjects = new Dictionary<string, Task<string>>();
foreach (ExpressionWithSource expressionWithSource in _expressionsWithSources)
{
Expression expression = expressionWithSource.Expression;
ExpressionSourceType source = expressionWithSource.Source;
Task<string> generatedTextTask = GenerateTextAsync(expression, source, cancellationToken);
string expressionNameResolvedDuplicates;
if (generatedTaskObjects.Keys.Contains(expression.Name))
{
int count = generatedTaskObjects.Keys.Count(x => x.StartsWith(expression.Name + " (")) + 1;
expressionNameResolvedDuplicates = expression.Name + " (" + count + ")";
}
else
{
expressionNameResolvedDuplicates = expression.Name;
}
generatedTaskObjects.Add(expressionNameResolvedDuplicates, generatedTextTask);
}
await Task.WhenAll(generatedTaskObjects.Values);
Dictionary<string, string> generatedObjects = generatedTaskObjects.ToDictionary(x => x.Key, y => y.Value.Result);
return generatedObjects;
}
示例6: SimpleAppClient
public SimpleAppClient(IRequester requester, Dictionary<Type, object> services)
: base(requester)
{
foreach (var pair in services)
{
Type iface = pair.Key;
if (iface == null)
{
throw new ApplicationException(); // todo2[ak]
}
if (!iface.IsInterface)
{
throw new ApplicationException(); // todo2[ak]
}
object instance = pair.Value;
if (instance == null)
{
throw new ApplicationException(); // todo2[ak]
}
if (!iface.IsAssignableFrom(instance.GetType()))
{
throw new ApplicationException(); // todo2[ak]
}
}
_proxies = services.ToDictionary(
pair => pair.Key.FullName,
pair => new Tuple<Type, object>(pair.Key, pair.Value));
}
示例7: BookPurchaseInfo
public BookPurchaseInfo BookPurchaseInfo(string totalBudget, Dictionary<string, string> purchaseBook)
{
BookPurchaseInfo thisPurchaseInfo = new BookPurchaseInfo();
if (String.IsNullOrWhiteSpace(totalBudget))
{
throw new NullReferenceException("Input field(s) is empty.");
}
else
{
try
{
thisPurchaseInfo.budget = float.Parse(totalBudget);
thisPurchaseInfo.items = purchaseBook.ToDictionary(
x => int.Parse(x.Key),
x => int.Parse(x.Value)
);
}
catch (Exception Ex)
{
throw new Exception(Ex.Message);
}
}
return thisPurchaseInfo;
}
示例8: IndependentMovements
public void IndependentMovements()
{
/* take a grid and populate with organisms: |___|_A_|___|_B_|___|___|___|___|___|___|
* make A choose rightmost stimulus & make B choose leftmost stimulus
* no conflict, both organisms should move where they chose to go
* result of test: |_A_|___|___|___|_B_|___|___|___|___|___| */
var organismHabitats = new Dictionary<Organism, Habitat>
{
{ this.organisms["A"], this.habitats[1, 0] },
{ this.organisms["B"], this.habitats[3, 0] }
};
var organismIntendedDestinations = new Dictionary<Organism, Habitat>
{
{ this.organisms["A"], this.habitats[0, 0] },
{ this.organisms["B"], this.habitats[4, 0] }
};
var expectedOrganismDestinations = organismIntendedDestinations.ToDictionary(
intendedDestination => intendedDestination.Key,
intendedDestination => intendedDestination.Value);
var updateSummary = this.CreateAndUpdateEcosystem(organismHabitats, organismIntendedDestinations);
var expectedCoordinates = expectedOrganismDestinations.Values.Select(expectedDestination => this.habitatCoordinates[expectedDestination]).ToList();
var actualCoordinates = updateSummary.PostUpdateOrganismLocations.Values.ToList();
Assert.That(actualCoordinates, Is.EqualTo(expectedCoordinates));
}
示例9: InputState
private InputState(SAMViewportAdapter adapter, KeyboardState ks, MouseState ms, TouchCollection ts, GamePadState gs, InputState prev)
{
Mouse = ms;
Keyboard = ks;
TouchPanel = ts;
GamePad = gs;
if (Mouse.LeftButton == ButtonState.Pressed)
{
IsDown = true;
PointerPosition = adapter.PointToScreen(Mouse.Position);
}
else if (TouchPanel.Count > 0)
{
IsDown = true;
PointerPosition = adapter.PointToScreen(TouchPanel[0].Position.ToPoint());
}
else
{
IsDown = false;
PointerPosition = prev.PointerPosition;
}
IsJustDown = IsDown && !prev.IsDown;
IsJustUp = !IsDown && prev.IsDown;
lastKeyState = prev.currentKeyState;
currentKeyState = lastKeyState.ToDictionary(p => p.Key, p => ks.IsKeyDown(p.Key));
}
示例10: Font
private Font(int height, Dictionary<char, byte[]> characters)
{
Height = height;
this.characters = characters.ToDictionary(
keyValue => keyValue.Key,
keyValue => new Character(keyValue.Value, height));
}
示例11: Lexer
/// <summary>
/// Initializes a new instance of the <see cref="Lexer" /> class.
/// </summary>
public Lexer()
{
// regex special characters (should be escaped if needed): .$^{[(|)*+?\
var patterns = new Dictionary<TokenType, string>
{
{TokenType.AND, @"&&"},
{TokenType.OR, @"\|\|"},
{TokenType.LEFT_BRACKET, @"\("},
{TokenType.RIGHT_BRACKET, @"\)"},
{TokenType.GE, @">="},
{TokenType.LE, @"<="},
{TokenType.GT, @">"},
{TokenType.LT, @"<"},
{TokenType.EQ, @"=="},
{TokenType.NEQ, @"!="},
{TokenType.NOT, @"!"},
{TokenType.NULL, @"null"},
{TokenType.COMMA, @","},
{TokenType.INC, @"\+{2}"}, // Despite the fact our language does not support ++ and -- prefix/postfix operations yet, these unary tokens are explicitly designated as illegal. We're detecting them to prevent unification which is done for consecutive plus or minus operators (e.g. + + - - +-+- => +).
{TokenType.DEC, @"\-{2}"}, // Unification of such unary operators breaks compatibility - such mixed 1++ + 2 operations are illegal in both C# and JavaScript (since we control C# side there is not pain here, but JavaScript would fail since we're sending raw expressions to client-side).
{TokenType.ADD, @"\+"},
{TokenType.SUB, @"-"},
{TokenType.MUL, @"\*"},
{TokenType.DIV, @"/"},
{TokenType.FLOAT, @"[0-9]*\.[0-9]+(?:[eE][\+-]?[0-9]+)?"}, // 1.0, 0.3e-2
{TokenType.INT, @"[0-9]+"},
{TokenType.BOOL, @"(?:true|false)"},
{TokenType.STRING, @"(['])(?:\\\1|.)*?\1"}, // '1234', 'John\'s cat'
{TokenType.FUNC, @"[a-zA-Z_]+(?:(?:(?:\[[0-9]+\])?\.[a-zA-Z_])?[a-zA-Z0-9_]*)*(?:\[[0-9]+\])?"} // field, field.field, arr[0], func(...)
};
RegexMap = patterns.ToDictionary(
kvp => kvp.Key,
kvp => new Regex(string.Format("^{0}", kvp.Value))); // in general, for compiled version of regular expressions their construction and initialization time is amortized out over many runs
}
示例12: IdentifyCustomer
public async Task<bool> IdentifyCustomer(string customerId, string email, DateTime? dateCreatedUtc = null, Dictionary<string, string> extraData = null)
{
if (string.IsNullOrWhiteSpace(customerId))
throw new ArgumentNullException("customerId may not be null or empty");
if (string.IsNullOrWhiteSpace(email))
throw new ArgumentNullException("email may not be null or empty");
var request = new HttpRequestMessage(HttpMethod.Put, new Uri(ApiUrl + customerId));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", SiteId, ApiKey))));
var dict = extraData == null ? new Dictionary<string, string>() : extraData.ToDictionary(d => d.Key, d => d.Value);
if (dict.ContainsKey("email"))
{
throw new ArgumentOutOfRangeException("extraData may not contain a key called 'email'");
}
dict.Add("email", email);
dict.Add("created_at",
dateCreatedUtc != null
? DateTimeToUnixTimestamp(dateCreatedUtc.Value).ToString("####")
: DateTimeToUnixTimestamp(DateTime.UtcNow).ToString("####"));
request.Content = new FormUrlEncodedContent(dict);
var response = await Client.SendAsync(request).ConfigureAwait(false);
return ProcessResponseAsync(response);
}
示例13: GroupGamesByGameInfo
public Dictionary<SportType, Dictionary<GameInfo, List<Game>>> GroupGamesByGameInfo(
Dictionary<SportType, List<Game>> games)
{
return games.ToDictionary(
gamesOfSport => gamesOfSport.Key,
gamesOfSport =>
{
var resultDict = new Dictionary<GameInfo, List<Game>>();
for (var i = 0; i < gamesOfSport.Value.Count; i++)
{
if (resultDict.Keys.All(info => info != gamesOfSport.Value[i].Info))
{
var tempList = new List<Game> { gamesOfSport.Value[i] };
for (var j = i + 1; j < gamesOfSport.Value.Count; j++)
{
if (gamesOfSport.Value[i].BetsName != gamesOfSport.Value[j].BetsName
& gamesOfSport.Value[i].Info == gamesOfSport.Value[j].Info)
{
tempList.Add(gamesOfSport.Value[j]);
}
}
resultDict.Add(gamesOfSport.Value[i].Info, tempList);
}
}
return resultDict.Where(x => x.Value.Count > 1).ToDictionary(t => t.Key, t => t.Value);
});
}
示例14: GetBatchSentimentAsync
public async Task<IDictionary<string, Result>> GetBatchSentimentAsync(Dictionary<string, string> textBatch)
{
ValidateBatchRequest(textBatch);
if (!textBatch.Any())
{
return new Dictionary<string, Result>();
}
string content;
using (var response = await _requestor.PostAsync(Constants.SentimentBatchRequest, BuildInputString(textBatch)))
{
content = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
return textBatch.ToDictionary(r => r.Key, r => AzureMachineLearningResult.Build(_errorMessageGenerator.GenerateError(response.StatusCode, content)));
}
}
var result = JsonConvert.DeserializeObject<SentimentBatchResult>(content);
var parsedResults = result.SentimentBatch.ToDictionary(sr => sr.Id, sr => AzureMachineLearningResult.Build(sr.Score, ScoreToSentiment(sr.Score)));
foreach (var error in result.Errors)
{
parsedResults.Add(error.Id, AzureMachineLearningResult.Build(error.Message));
}
return parsedResults;
}
示例15: Prepare
internal override void Prepare()
{
Contract.Requires(!String.IsNullOrWhiteSpace(Database));
Contract.Requires(!String.IsNullOrWhiteSpace(Username));
var parameters = new Dictionary<String, String> {
{ "database", Database },
{ "user", Username },
{ "client_encoding", "UTF8" },
};
if (ApplicationName != null)
{
parameters.Add("application_name", ApplicationName);
}
if (SearchPath != null)
{
parameters.Add("search_path", SearchPath);
}
// TODO: Is this really UTF8 or can be ASCII?
_parameters = parameters.ToDictionary(kv => PGUtil.UTF8Encoding.GetBytes(kv.Key),
kv => PGUtil.UTF8Encoding.GetBytes(kv.Value));
_length = 4 + // len
4 + // protocol version
_parameters.Select(kv => kv.Key.Length + kv.Value.Length + 2).Sum() +
1; // trailing zero byte
}