本文整理汇总了C#中System.ToDictionary方法的典型用法代码示例。如果您正苦于以下问题:C# System.ToDictionary方法的具体用法?C# System.ToDictionary怎么用?C# System.ToDictionary使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System
的用法示例。
在下文中一共展示了System.ToDictionary方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestReferenceTypeKeyDuplicate
public void TestReferenceTypeKeyDuplicate()
{
string[] strings = new [] {"0", "1", "1"};
Assert.Throws<ArgumentException> (() => strings.ToDictionary (keySelector: it => it));
Assert.Throws<ArgumentException> (() => strings.ToDictionary (keySelector: it => it, elementSelector: it => it));
Assert.Throws<ArgumentException> (() => strings.ToDictionary (keySelector: it => it, comparer: EqualityComparer<string>.Default));
Assert.Throws<ArgumentException> (() => strings.ToDictionary (keySelector: it => it, elementSelector: it => it, comparer: EqualityComparer<string>.Default));
}
示例2: should_return_dictionary_containing_types_properties
public void should_return_dictionary_containing_types_properties()
{
var anonymousType = new { Jelly = "Donut", Strings = "Guitar", Watson = "Holmes", Simon = "Garfunkel" };
anonymousType.ToDictionary().ShouldContainKeyAndValue("Jelly", "Donut");
anonymousType.ToDictionary().ShouldContainKeyAndValue("Strings", "Guitar");
anonymousType.ToDictionary().ShouldContainKeyAndValue("Watson", "Holmes");
anonymousType.ToDictionary().ShouldContainKeyAndValue("Simon", "Garfunkel");
}
示例3: TestReferenceType_NullKeyExceptions
public void TestReferenceType_NullKeyExceptions()
{
string[] strings = new [] {"0", "1", "2", "3", "4", "5", "6"};
IEqualityComparer<string> comparer = EqualityComparer<string>.Default;
Func<string, string> nullKeyFunc = it => null;
Func<string, string> func = it => it;
Assert.Throws<ArgumentNullException> (() => strings.ToDictionary<string, string> (keySelector: nullKeyFunc));
Assert.Throws<ArgumentNullException> (() => strings.ToDictionary<string, string> (keySelector: nullKeyFunc, comparer: comparer));
Assert.Throws<ArgumentNullException> (() => strings.ToDictionary<string, string, string> (keySelector: nullKeyFunc, elementSelector: func));
Assert.Throws<ArgumentNullException> (() => strings.ToDictionary<string, string, string> (keySelector: nullKeyFunc, elementSelector: func, comparer: comparer));
}
示例4: RiskPanel
/// <summary>
/// Initializes a new instance of the <see cref="RiskPanel"/>.
/// </summary>
public RiskPanel()
{
InitializeComponent();
var ruleTypes = new[]
{
typeof(RiskCommissionRule),
typeof(RiskOrderFreqRule),
typeof(RiskOrderPriceRule),
typeof(RiskOrderVolumeRule),
typeof(RiskPnLRule),
typeof(RiskPositionSizeRule),
typeof(RiskPositionTimeRule),
typeof(RiskSlippageRule),
typeof(RiskTradeFreqRule),
typeof(RiskTradePriceRule),
typeof(RiskTradeVolumeRule)
};
_names.AddRange(ruleTypes.ToDictionary(t => t, t => t.GetDisplayName()));
TypeCtrl.ItemsSource = _names;
TypeCtrl.SelectedIndex = 0;
var itemsSource = new ObservableCollectionEx<RuleItem>();
RuleGrid.ItemsSource = itemsSource;
_rules = new ConvertibleObservableCollection<IRiskRule, RuleItem>(new ThreadSafeObservableCollection<RuleItem>(itemsSource), CreateItem);
}
示例5: TableMapping_ColumnsCount_Contracts
public void TableMapping_ColumnsCount_Contracts()
{
using (var ctx = GetContext())
{
var allTypes = new[]
{
typeof (ContractBase),
typeof (Contract),
typeof (ContractFixed),
typeof (ContractStock),
typeof (ContractKomb1),
typeof (ContractKomb2),
};
var mappings = allTypes.ToDictionary(x => x, ctx.Db);
using (var dataTable = DataTableHelper.Create(mappings, new ContractBase[0]))
{
foreach (DataColumn column in dataTable.Columns)
{
Console.WriteLine(column.ColumnName);
}
Assert.AreEqual(34, dataTable.Columns.Count);
}
}
}
示例6: LoanApprovalUserControl
public LoanApprovalUserControl()
{
InitializeComponent();
var statuses = new[]
{
OContractStatus.Pending,
OContractStatus.Validated,
OContractStatus.Refused,
OContractStatus.Abandoned,
OContractStatus.Deleted,
OContractStatus.Postponed
};
var resourceManager = new ResourceManager("OpenCBS.Extensions.Resources.Extensions", GetType().Assembly);
var dict = statuses.ToDictionary(x => x, x => resourceManager.GetString(x.ToString()));
_statusComboBox.DisplayMember = "Value";
_statusComboBox.ValueMember = "Key";
_statusComboBox.DataSource = new BindingSource(dict, null);
_statusComboBox.SelectedIndex = 0;
_saveButton.Click += (sender, args) =>
{
if (SaveLoanApproval == null) return;
SaveLoanApproval();
};
this._dateTimePicker.Format = DateTimePickerFormat.Custom;
this._dateTimePicker.CustomFormat = ApplicationSettings.GetInstance("").SHORT_DATE_FORMAT;
}
示例7: CommissionPanel
/// <summary>
/// Initializes a new instance of the <see cref="CommissionPanel"/>.
/// </summary>
public CommissionPanel()
{
InitializeComponent();
var itemsSource = new ObservableCollectionEx<RuleItem>();
RuleGrid.ItemsSource = itemsSource;
_rules = new ConvertibleObservableCollection<ICommissionRule, RuleItem>(new ThreadSafeObservableCollection<RuleItem>(itemsSource), CreateItem);
var ruleTypes = new[]
{
typeof(CommissionPerOrderCountRule),
typeof(CommissionPerOrderRule),
typeof(CommissionPerOrderVolumeRule),
typeof(CommissionPerTradeCountRule),
typeof(CommissionPerTradePriceRule),
typeof(CommissionPerTradeRule),
typeof(CommissionPerTradeVolumeRule),
typeof(CommissionSecurityIdRule),
typeof(CommissionSecurityTypeRule),
typeof(CommissionTurnOverRule),
typeof(CommissionBoardCodeRule)
};
_names.AddRange(ruleTypes.ToDictionary(t => t, t => t.GetDisplayName()));
TypeCtrl.ItemsSource = _names;
TypeCtrl.SelectedIndex = 0;
}
示例8: BinaryLogicalOperator
public BinaryLogicalOperator(IElementCreationContext context, BinaryLogicalOperatorType defaultType)
: base(context, context.Owner.GetBooleanType())
{
ParameterA = context.Owner.CreateParameter("a", context.Owner.GetBooleanType());
ParameterB = context.Owner.CreateParameter("b", context.Owner.GetBooleanType());
Parameters.Add(ParameterA);
Parameters.Add(ParameterB);
var services = new[]
{
new BinaryLogicalOperatorService(BinaryLogicalOperatorType.And, "And", (a, b) => a && b),
new BinaryLogicalOperatorService(BinaryLogicalOperatorType.Or, "Or", (a, b) => a || b),
};
foreach (var service in services)
{
AddAction(new ElementAction(service.Text, () => OperatorType = service.Type));
}
_services = services.ToDictionary(s => s.Type, s => s);
OperatorType = defaultType;
if (!string.IsNullOrWhiteSpace(context.Data))
{
var data = JsonConvert.DeserializeObject<BinaryLogicalOperatorData>(context.Data);
OperatorType = data.OperatorType;
}
}
示例9: Main
public static void Main(string[] args)
{
var parser = new Parser();
Directory.SetCurrentDirectory(@"C:\dev\oss\less.js\test\less");
var files = new[]
{
"colors",
"comments",
"css",
"css-3",
"lazy-eval",
"mixins",
"mixins-args",
"operations",
"parens",
"rulesets",
"scope",
"selectors",
"strings",
"variables",
"whitespace"
}
.Select(f => f + ".less");
var contents = files
.ToDictionary(f => f, f => File.ReadAllText(f));
const int rounds = 150;
Func<string, int> runTest = file => Enumerable
.Range(0, rounds)
.Select(i =>
{
var starttime = DateTime.Now;
parser.Parse(contents[file]).ToCSS(null);
var duration = (DateTime.Now - starttime);
return duration.Milliseconds;
})
.Sum();
Console.WriteLine("Press Enter to begin benchmark");
Console.ReadLine();
Console.WriteLine("Running each test {0} times", rounds);
foreach (var file in files)
{
var size = rounds*contents[file].Length/1024d;
Console.Write("{0} : {1,7:#,##0.00} Kb ", file.PadRight(18), size);
var time = runTest(file)/1000d;
Console.WriteLine("{0,6:#.00} s {1,8:#,##0.00} Kb/s", time, size/time);
}
// Console.Read();
}
示例10: ToDictionaryKeyEqualityComparer_CaseInsensitiveEqualityComparer_Throws
public void ToDictionaryKeyEqualityComparer_CaseInsensitiveEqualityComparer_Throws()
{
var instance = new[]
{
new KeyValuePair<string, int>("a", 1), new KeyValuePair<string, int>("b", 2),
new KeyValuePair<string, int>("A", 3)
};
var actual = instance.ToDictionary(StringComparer.InvariantCultureIgnoreCase);
}
示例11: TestMethod
public void TestMethod()
{
var doclist = new[] {
new {RelatingDocument = "Doc1", RelatedObjects = new List<string>() { "Ent1", "Ent2", "Ent3", "Ent4", "Ent5" } },
new {RelatingDocument = "Doc1", RelatedObjects = new List<string>() { "Ent1", "Ent6", "Ent7" } },
new {RelatingDocument = "Doc1", RelatedObjects = new List<string>() { "Ent8", "Ent9" } },
new {RelatingDocument = "Doc2", RelatedObjects = new List<string>() { "Ent1", "Ent6", "Ent7" } },
new {RelatingDocument = "Doc3", RelatedObjects = new List<string>() { "Ent1", "Ent6" } },
new {RelatingDocument = "Doc4", RelatedObjects = new List<string>() { "Ent1", "Ent2", "Ent7" } },
new {RelatingDocument = "Doc5", RelatedObjects = new List<string>() { "Ent1", "Ent2", "Ent3" } },
new {RelatingDocument = "Doc1", RelatedObjects = new List<string>() { "Ent10", "Ent11" } },
new {RelatingDocument = "Doc2", RelatedObjects = new List<string>() { "Ent10", "Ent11" } },
}.ToList();
Dictionary<string, List<string>> dic = null;
//check for duplicates
var dups = doclist.GroupBy(d => d.RelatingDocument).SelectMany(grp => grp.Skip(1));
//combine object lists to single key value, merge lists
var dupsMerge = dups.GroupBy(d => d.RelatingDocument).Select(p => new { x = p.Key, y = p.SelectMany(c => c.RelatedObjects) });
if (dupsMerge.Any())
{
//remove the duplicates and convert to dictionary
dic = doclist.Except(dups).ToDictionary(p => p.RelatingDocument, p => p.RelatedObjects);
//add the duplicate doc referenced object lists to the original doc
foreach (var item in dupsMerge)
{
dic[item.x] = dic[item.x].Union(item.y).ToList();
}
}
else
{
//no duplicates, so just convert to dictionary
dic = doclist.ToDictionary(p => p.RelatingDocument, p => p.RelatedObjects);
}
//reverse lookup to entity to list of documents
var newDic = dic
.SelectMany(pair => pair.Value
.Select(val => new { Key = val, Value = pair.Key }))
.GroupBy(item => item.Key)
.ToDictionary(gr => gr.Key, gr => gr.Select(item => item.Value));
Assert.AreEqual(newDic["Ent1"].Count(), 5);
Assert.AreEqual(newDic["Ent2"].Count(), 3);
Assert.AreEqual(newDic["Ent3"].Count(), 2);
Assert.AreEqual(newDic["Ent4"].Count(), 1);
Assert.AreEqual(newDic["Ent5"].Count(), 1);
Assert.AreEqual(newDic["Ent6"].Count(), 3);
Assert.AreEqual(newDic["Ent7"].Count(), 3);
Assert.AreEqual(newDic["Ent8"].Count(), 1);
Assert.AreEqual(newDic["Ent9"].Count(), 1);
Assert.AreEqual(newDic["Ent10"].Count(), 2);
Assert.AreEqual(newDic["Ent11"].Count(), 2);
}
示例12: Linq56
public void Linq56()
{
var scoreRecords = new[] { new {Name = "Alice", Score = 50},
new {Name = "Bob" , Score = 40},
new {Name = "Cathy", Score = 45}
};
var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
Console.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]);
}
示例13: AnonToDict
public void AnonToDict()
{
object anon = new { width = 30, length = 45 };
Dictionary<string, object> dict = anon.ToDictionary();
Assert.IsTrue(dict.ContainsKey("width"));
Assert.AreEqual(30, (int)dict["width"]);
Assert.IsTrue(dict.ContainsKey("length"));
Assert.AreEqual(45, (int)dict["length"]);
}
示例14: ToDictionaryNoEqualityComparer_TwoKeysOnlyCaseDifferent_ReturnsDictionaryOfSourceLength
public void ToDictionaryNoEqualityComparer_TwoKeysOnlyCaseDifferent_ReturnsDictionaryOfSourceLength()
{
var instance = new[]
{
new KeyValuePair<string, int>("a", 1), new KeyValuePair<string, int>("b", 2),
new KeyValuePair<string, int>("A", 3)
};
var expected = 3;
var actual = instance.ToDictionary().Count;
Assert.AreEqual(expected, actual);
}
示例15: TestReferenceType_ReferenceKey
public void TestReferenceType_ReferenceKey()
{
string[] strings = new [] {"0", "1", "2", "3", "4", "5", "6"};
Dictionary<string, string> dict = strings.ToDictionary (keySelector: it => it);
Assert.That (dict.Count, Is.EqualTo (strings.Length));
foreach (string element in strings) {
Assert.That (dict [element], Is.EqualTo (element));
}
}