本文整理汇总了C#中System.Collections.Dictionary.ElementAt方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.ElementAt方法的具体用法?C# Dictionary.ElementAt怎么用?C# Dictionary.ElementAt使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Collections.Dictionary
的用法示例。
在下文中一共展示了Dictionary.ElementAt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SetData
// public int itemCount = 10, columnCount = 1;
// void Start()
// {
// Dictionary<string, string> dict = new Dictionary<string, string> ();
// dict.Add ("1", "assdsdasd");
// dict.Add ("2", "bytyter");
// dict.Add ("3", "trwegvbtrw");
// dict.Add ("4", "45123412");
// dict.Add ("5", "tgtv52345");
// dict.Add ("6", "4321fff43214");
// dict.Add ("7", "123412f43");
// SetData (null, dict);
// }
public void SetData(Action<string> onItemClickAction, Dictionary<string, string> objects)
{
int itemCount = objects.Count;
int columnCount = 1;
items = new List<GameObject> (columnCount);
RectTransform rowRectTransform = itemPrefab.GetComponent<RectTransform> ();
RectTransform containerRectTransform = gameObject.GetComponent<RectTransform> ();
//calculate the width and height of each child item.
float width = containerRectTransform.rect.width / columnCount;
float ratio = width / rowRectTransform.rect.width;
float height = rowRectTransform.rect.height * ratio;
int rowCount = itemCount / columnCount;
if (itemCount % rowCount > 0)
rowCount++;
//adjust the height of the container so that it will just barely fit all its children
float scrollHeight = height * rowCount;
containerRectTransform.offsetMin = new Vector2 (containerRectTransform.offsetMin.x, -scrollHeight / 2);
containerRectTransform.offsetMax = new Vector2 (containerRectTransform.offsetMax.x, scrollHeight / 2);
int j = 0;
for (int i = 0; i < itemCount; i++) {
//this is used instead of a double for loop because itemCount may not fit perfectly into the rows/columns
if (i % columnCount == 0)
j++;
//create a new item, name it, and set the parent
GameObject newItem = Instantiate (itemPrefab) as GameObject;
newItem.name = gameObject.name + " item at (" + i + "," + j + ")";
newItem.transform.SetParent(gameObject.transform);
Text textField = newItem.GetComponentsInChildren<Text> (true)[0];
KeyValuePair<string, string> o = objects.ElementAt(i);//.Keys.ElementAt2(i);
textField.text = o.Value;
if (onItemClickAction != null) {
newItem.GetComponents<Button>()[0].onClick.AddListener (() => {onItemClickAction(o.Key);});
}
items.Add(newItem);
//move and size the new item
RectTransform rectTransform = newItem.GetComponent<RectTransform> ();
float x = -containerRectTransform.rect.width / 2 + width * (i % columnCount);
float y = containerRectTransform.rect.height / 2 - height * j;
rectTransform.offsetMin = new Vector2 (x, y);
x = rectTransform.offsetMin.x + width;
y = rectTransform.offsetMin.y + height;
rectTransform.offsetMax = new Vector2 (x, y);
}
}
示例2: TestReader_FromFactory
public void TestReader_FromFactory()
{
string filepath = this.WriteTextToTempFile(Consts.ResxSample01, ".resx");
using (ILocanReader reader = LocanReaderWriterFactory.Instance.GetReader(new { filepath = filepath })) {
Dictionary<string, string> expectedValues = new Dictionary<string, string>();
expectedValues.Add("Key01", "Value01");
expectedValues.Add("Key02", "Value02");
expectedValues.Add("Key03", "Value03");
int currentIndex = 0;
foreach (ILocanRow row in reader.GetRowsToBeTranslated()) {
string expectedKey = expectedValues.ElementAt(currentIndex).Key;
string expectedValue = expectedValues.ElementAt(currentIndex).Value as string;
Assert.AreEqual(expectedKey, row.Id);
Assert.AreEqual(expectedValue, row.StringToTranslate);
currentIndex++;
}
}
}
示例3: Max
//Given a sequence of non-negative integers find a subsequence of length 3 having maximum product with the numbers of the subsequence being in ascending order.
//Example:
//Input: 6 7 8 1 2 3 9 10
//Ouput: 8 9 10
//Wrong!!!
public List<int> Max(int[] a)
{
Dictionary<List<int>, int> result = new Dictionary<List<int>, int>();
List<int> list = new List<int>();
list.Add(a[0]);
result.Add(list, a[0]);
int max = 0, min = 0;
for (int i = 1; i < a.Length; i++)
{
min = result.Values.Min();
max = result.Values.Max();
if (a[i] >= max)
{
list = result.FirstOrDefault(x => x.Value == max).Key;
list.Add(a[i]);
result[list] = a[i];
if (list.Count > 3)
list.RemoveAt(0);
}
else if (a[i] <= min)
{
list = new List<int>();
list.Add(a[i]);
result.Add(list, a[i]);
}
else
{
for(int x=0;x<result.Count;x++)
{
var t = result.ElementAt(x);
if (t.Value < a[i])
{
t.Key.Add(a[i]);
result[t.Key] = a[i];
if (t.Key.Count > 3)
t.Key.RemoveAt(0);
}
}
}
}
max = result.Values.Max();
list = result.FirstOrDefault(x => x.Value == max).Key;
return list;
}
示例4: MyRemoveduplicate
static void MyRemoveduplicate(int seed)
{
//其实用字典更好,应该字典可以保证没有重复的值
//.NET如果添加重复的键会抛异常(Fuck)
//JAVA会覆盖具有相同键的值
Dictionary<int, int> dic = new Dictionary<int, int>();
Random rm = new Random(seed);
int RmNum = 10;
while (RmNum > dic.Count)
{
int nValue = rm.Next(20);
if (dic.ContainsKey(nValue))
continue;
dic.Add(nValue, nValue);
}
for (int i = 0; i < dic.Count; i++)
{
Console.Write(dic.ElementAt(i).Value+" ");
}
Console.Write("\n");
}
示例5: loadLocalData
public void loadLocalData()
{
Dictionary<string, Task> loadedTasks = null;
TasksDict = null;
FileStream fs = new FileStream(path, FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
loadedTasks = (Dictionary<string, Task>)formatter.Deserialize(fs);
TasksDict = loadedTasks;
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
//selectedTask = TasksDict.ElementAt(0).Value;
user = TasksDict.ElementAt(0).Value.executor;
fs.Close();
}
}
示例6: SetDefaultGrabber
public static void SetDefaultGrabber()
{
GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_MENU);
if (dlg == null)
{
return;
}
dlg.Reset();
dlg.SetHeading(1263); // menu
// read index file
if (!File.Exists(_grabberIndexFile))
{
GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_OK);
dlgOk.SetHeading(257);
dlgOk.SetLine(1, GUILocalizeStrings.Get(1261)); // No grabber index found
dlgOk.DoModal(GUIWindowManager.ActiveWindow);
return;
}
_grabberList = new Dictionary<string, ComboBoxItemDatabase>();
Directory.CreateDirectory(IMDB.ScriptDirectory);
DirectoryInfo di = new DirectoryInfo(IMDB.ScriptDirectory);
FileInfo[] fileList = di.GetFiles("*.csscript", SearchOption.AllDirectories);
GUIWaitCursor.Show();
foreach (FileInfo f in fileList)
{
try
{
CSScript.GlobalSettings.AddSearchDir(AppDomain.CurrentDomain.BaseDirectory);
using (AsmHelper script = new AsmHelper(CSScript.Compile(f.FullName), "Temp", true))
{
script.ProbingDirs = CSScript.GlobalSettings.SearchDirs.Split(';');
IIMDBScriptGrabber grabber = (IIMDBScriptGrabber) script.CreateObject("Grabber");
ComboBoxItemDatabase item = new ComboBoxItemDatabase();
item.Database = Path.GetFileNameWithoutExtension(f.FullName);
item.Language = grabber.GetLanguage();
item.Limit = IMDB.DEFAULT_SEARCH_LIMIT.ToString();
item.Name = grabber.GetName();
_grabberList.Add(item.Database, item);
}
}
catch (Exception ex)
{
Log.Error("Script grabber error file: {0}, message : {1}", f.FullName, ex.Message);
}
}
string defaultDatabase = string.Empty;
int defaultIndex = 0;
int dbNumber;
using (Profile.Settings xmlreader = new MPSettings())
{
defaultDatabase = xmlreader.GetValueAsString("moviedatabase", "database" + 0, "IMDB");
dbNumber = xmlreader.GetValueAsInt("moviedatabase", "number", 0);
}
foreach (KeyValuePair<string, ComboBoxItemDatabase> grabber in _grabberList)
{
dlg.Add(grabber.Value.Name + " - " + grabber.Value.Language);
if (defaultDatabase == grabber.Key)
{
dlg.SelectedLabel = defaultIndex;
}
else
{
defaultIndex++;
}
}
GUIWaitCursor.Hide();
dlg.DoModal(GUIWindowManager.ActiveWindow);
if (dlg.SelectedId == -1)
{
return;
}
using (Profile.Settings xmlwriter = new MPSettings())
{
KeyValuePair<string, ComboBoxItemDatabase> grabber = _grabberList.ElementAt(dlg.SelectedLabel);
if (grabber.Key != "IMDB")
{
if (dbNumber == 0)
{
dbNumber = 1;
}
xmlwriter.SetValue("moviedatabase", "number", dbNumber);
//.........这里部分代码省略.........
示例7: Main
static void Main(string[] args)
{
// Даны два неубывающих массива x и y. Найти их пересечение, то есть неубывающий массив z, содержащий их общие элементы,
//причем кратность каждого элемента в массиве z равна минимуму его кратностей в массивах x и y.
const int firstLength = 7;
const int secondLength = 6;
float[] firstArray = new float[firstLength] { 1, 3, 4, 4, 5, 5, 5 };
float[] secondArray = new float[secondLength] { 1, 4, 4, 4, 5, 5 };
ArrayList thirdArray = new ArrayList();
//Словари для подсчета количества каждой цифры в соответствующем массиве
Dictionary<float, int> firstDict = new Dictionary<float, int>();
Dictionary<float, int> secondDict = new Dictionary<float, int>();
Program pr = new Program();
firstDict = pr.digitsAmountDict(firstArray, firstDict);
secondDict = pr.digitsAmountDict(secondArray, secondDict);
//Зная количество каждой цифры в обоих массивах, выводим в результирующий массив наименьшее их количество,
//и только тех, которые существуют в обоих массивах
for (int i = 0; i < firstDict.Count; i++)
{
for (int j = 0; j < secondDict.Count; j++)
{
var itemFirstDict = firstDict.ElementAt(i);
var itemSecondDict = secondDict.ElementAt(j);
if (itemFirstDict.Key == itemSecondDict.Key)
{
/*if (itemFirstDict.Value <= itemSecondDict.Value)
{
for (int k = 0; k < itemFirstDict.Value; k++)
{
thirdArray.Add(itemFirstDict.Key);
}
}
else
{
for (int l = 0; l < itemSecondDict.Value; l++)
{
thirdArray.Add(itemSecondDict.Key);
}
}*/
for (int k = 0; k < Math.Min(itemFirstDict.Value, itemSecondDict.Value); k++)
{
thirdArray.Add(itemSecondDict.Key);
}
}
}
}
Console.WriteLine("Элементы первого массива:");
for (int m = 0; m < firstArray.Length; m++)
{
Console.Write(" " + firstArray[m]);
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Элементы второго массива:");
for (int m = 0; m < secondArray.Length; m++)
{
Console.Write(" " + secondArray[m]);
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Элементы результирующего массива:");
for (int m = 0; m < thirdArray.Count; m++)
{
Console.Write(" " + thirdArray[m]);
}
Console.ReadKey();
}
示例8: Minimize
/// <summary>
/// Machine minimization. EnableEvents must be used before to enable this method.
/// </summary>
public void Minimize()
{
bool hasMinimization = false;
#region Minimization
// find minimizable states
Dictionary<string, List<string>> minimizableStates = new Dictionary<string, List<string>>();
foreach (State s in this.States) {
foreach (State ss in this.States) {
if (ss.Name != s.Name) {
if (this.IsMirrorState(ss, s)) {
if (minimizableStates.Keys.Contains(s.Name))
minimizableStates[s.Name].Add(ss.Name);
else
minimizableStates.Add(s.Name, new List<string>() { ss.Name });
}
}
}
}
//update transitions
for (int i = 0; i < minimizableStates.Count - 1; i++) {
string stateName = minimizableStates.ElementAt(i).Key;
List<string> stateEquiv = minimizableStates.ElementAt(i).Value;
string newStateName = stateName;
foreach (string s in stateEquiv)
newStateName += "|" + s;
State mergedState = new State(newStateName);
minimizableStates.ElementAt(i).Value.Add(stateName);
foreach (string s in stateEquiv) {
minimizableStates.Remove(s);
State toRemove = (from State ss in this.States where ss.Name == s select ss).First();
foreach (Transition t in this.Transitions){
if (t.SourceState.Equals(toRemove))
t.SourceState = mergedState;
if (t.TargetState.Equals(toRemove))
t.TargetState = mergedState;
}
this.States.Remove(toRemove);
}
hasMinimization = true;
}
List<Transition> newTransitions = new List<Transition>();
foreach (Transition t in this.Transitions)
if (!newTransitions.Contains(t))
newTransitions.Add(t);
this.Transitions = newTransitions;
#endregion
//Re-apply minimination if machine has been modified
if (hasMinimization)
this.Minimize();
}
示例9: UpdateView
private void UpdateView()
{
var unitDict = new Dictionary<string, TestModel>();
var sections = from test in _sectionModel.Cast<TestModel>()
group test by test.MasterAgentIp
into unit
select new { unit.Key, Tests = unit };
foreach (var section in sections.ToList())
{
IList<TestModel> tests = section.Tests.OrderBy(t => t.TestId).ToList();
bool allGood = true;
var syndromSb = new StringBuilder();
foreach (TestModel test in tests)
{
if (test.Status != "Stan poprawny")
allGood = false;
syndromSb.Append(test.Status == "Stan poprawny" ? "0" : "1");
}
foreach (TestModel test in tests)
{
if (!unitDict.Keys.Contains(test.IpDest))
{
unitDict.Add(test.IpDest,
new TestModel
{
IpDest = test.IpDest,
MasterAgentIp = section.Key,
Status = "Stan poprawny"
});
}
else
{
unitDict[test.IpDest].Status = "Stan poprawny";
}
}
if (!allGood)
{
IList<SyndromModel> syndromList = _dataProvider.FindGlobalOpinion(section.Key);
bool opinionMatch = false;
foreach (
SyndromModel syndromModel in
syndromList.Where(syndromModel => SyndromsMatch(syndromModel.Syndrom, syndromSb.ToString()))
)
{
opinionMatch = true;
string[] failedHostsList = syndromModel.Hosts.TrimEnd(',').Split(',');
foreach (string host in failedHostsList)
{
unitDict[host].Status = "Stan NIEpoprawny";
}
}
if (!opinionMatch)
{
foreach (TestModel test in tests)
{
unitDict[test.IpDest].Status = "Brak pasującego syndromu";
}
}
}
}
for (int i = 0; i < unitDict.Count; i++)
{
unitDict.ElementAt(i).Value.TestId = i;
}
var groupedSectionModels = new ListCollectionView(_sectionModel);
groupedSectionModels.GroupDescriptions.Add(new PropertyGroupDescription("MasterAgentIp"));
var groupedUnitModels = new ListCollectionView(unitDict.Values.ToList());
groupedUnitModels.GroupDescriptions.Add(new PropertyGroupDescription("MasterAgentIp"));
UnitGrid.ItemsSource = groupedUnitModels;
SectionGrid.ItemsSource = groupedSectionModels;
}
示例10: ShowFilteredThumbnails
public void ShowFilteredThumbnails(ObservableCollection<string> itemsToFilter)
{
Dictionary<string, string> categoryAndName = new Dictionary<string, string>();
List<string> gymnastValues = new List<string>();
List<string> locationValues = new List<string>();
List<string> vaultNumberValues = new List<string>();
List<string> dateValues = new List<string>();
List<decimal> eRatings = new List<decimal>();
List<decimal> dRatings = new List<decimal>();
for (int k = 0; k < itemsToFilter.Count; k++)
{
categoryAndName.Add(itemsToFilter[k].Split(':')[1], itemsToFilter[k].Split(':')[0]);
}
for (int j = 0; j < categoryAndName.Count; j++)
{
if (categoryAndName.ElementAt(j).Value.Equals("Gymnast"))
{
gymnastValues.Add(categoryAndName.ElementAt(j).Key);
}
else if (categoryAndName.ElementAt(j).Value.Equals("Location"))
{
locationValues.Add(categoryAndName.ElementAt(j).Key);
}
else if(categoryAndName.ElementAt(j).Value.Equals("Vault"))
{
vaultNumberValues.Add(categoryAndName.ElementAt(j).Key);
}
else if(categoryAndName.ElementAt(j).Value.Equals("Date"))
{
dateValues.Add(categoryAndName.ElementAt(j).Key);
}
}
List<vault> newVaults = vaultModule.filter(dRatings, eRatings, gymnastValues, locationValues, vaultNumberValues,dateValues);
modifyVaultVM.setData(newVaults);
OnPropertyChanged("ModifyViewModelControl");
}
示例11: OrderItemAddPage
/// <summary>
/// 订单商品添加页面
/// </summary>
/// <returns></returns>
public ActionResult OrderItemAddPage()
{
//搜索字段的下拉框
List<SelectListItem> listSearchProperty = new List<SelectListItem>();
Dictionary<string, string> dictionaryProperty = new Dictionary<string, string>();
dictionaryProperty.Add(LiveAzure.Resource.Model.Product.ProductInfoItem.Code,"Code");
dictionaryProperty.Add(LiveAzure.Resource.Model.Product.ProductOnItem.FullName,"FullName");
for (int i = 0; i < dictionaryProperty.Count; i++)
{
listSearchProperty.Add(new SelectListItem { Text = dictionaryProperty.ElementAt(i).Key, Value = dictionaryProperty.ElementAt(i).Value });
}
ViewBag.SearchProperty = listSearchProperty;
//搜索条件的下拉框
List<SelectListItem> listSearchMode = new List<SelectListItem>();
Dictionary<string, string> dictionaryModes = new Dictionary<string, string>();
dictionaryModes.Add("以...开头", "0");
dictionaryModes.Add("包含", "1");
dictionaryModes.Add("以...结尾", "2");
for (int i = 0; i < dictionaryModes.Count; i++)
{
listSearchMode.Add(new SelectListItem { Text = dictionaryModes.ElementAt(i).Key, Value = dictionaryModes.ElementAt(i).Value });
}
ViewBag.SearchMode = listSearchMode;
return View();
}
示例12: GenerateMethod
private void GenerateMethod(Type interfaceType, FieldBuilder handlerField, TypeBuilder typeBuilder) {
MetaDataFactory.Add(interfaceType);
// Obtém a lista de todos os métodos a serem criados.
MethodInfo[] interfaceMethods = interfaceType.GetMethods().OrderBy(p => p.Name).ToArray();
// Verifica se existe algum método a ser implementado na interface.
if (interfaceMethods != null) {
// Cria cada um dos métodos definidos na interface.
for (int i = 0; i < interfaceMethods.Length; i++) {
MethodInfo methodInfo = interfaceMethods[i];
// Obtém os parâmetros do método que está sendo criado.
ParameterInfo[] methodParams = methodInfo.GetParameters();
int numOfParams = methodParams.Length;
Type[] methodParameters = new Type[numOfParams];
// Armazena o tipo de cada parâmetro do método.
for (int j = 0; j < numOfParams; j++) {
methodParameters[j] = methodParams[j].ParameterType;
}
// Armazena todos os tipos genéricos do método.
Type[] genericArguments = methodInfo.GetGenericArguments();
MethodBuilder methodBuilder = null;
// Verifica se o método não possui tipos genéricos.
if (genericArguments.Length == 0) {
// Cria um MethodBuilder para o método da interface que esta sendo criado. Como não há tipos genéricos, a definição é feita em apenas uma etapa.
methodBuilder = typeBuilder.DefineMethod(
methodInfo.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
CallingConventions.Standard,
methodInfo.ReturnType, methodParameters);
}
else {
// Cria um MethodBuilder que deverá ser preenchido em etapas, pois os tipos genéricos do método precisam ser identificados.
methodBuilder = typeBuilder.DefineMethod(
methodInfo.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
CallingConventions.Standard);
// Define o tipo de retorno do método.
methodBuilder.SetReturnType(methodInfo.ReturnType);
Dictionary<int, string> typeParamNames = new Dictionary<int, string>();
Dictionary<int, Type> parameters = new Dictionary<int, Type>();
int currentIndex = 0;
// Analisa todos os parâmetros do método.
foreach (ParameterInfo parameterInfo in methodParams) {
// Caso o parâmetro não possua a propriedade FullName preenchida, indica que é um tipo genérico. Caso contrário, é um tipo forte.
if (parameterInfo.ParameterType.FullName == null) {
typeParamNames.Add(currentIndex, parameterInfo.ParameterType.Name);
}
else {
parameters.Add(currentIndex, parameterInfo.ParameterType);
}
currentIndex++;
}
// Verifica se existe algum tipo genérico.
if (typeParamNames.Count > 0) {
// Informa ao MethodBuilder os nomes dos tipos genéricos.
GenericTypeParameterBuilder[] typeParameters = methodBuilder.DefineGenericParameters(typeParamNames.Values.ToArray());
// Adiciona os tipos genéricos na lista de tipos do método.
for (int j = 0; j < typeParameters.Length; j++) {
int parameterIndex = typeParamNames.ElementAt(j).Key;
parameters.Add(parameterIndex, typeParameters[j]);
}
// Define o tipo de retorno do método.
methodBuilder.SetReturnType(methodInfo.ReturnType);
}
// Verifica se o tipo de retorno é um tipo genérico.
else if (methodInfo.ReturnType.IsGenericParameter == true) {
// Informa ao MethodBuilder o nome do tipo genérico.
GenericTypeParameterBuilder[] returnParameter = methodBuilder.DefineGenericParameters(methodInfo.ReturnType.Name);
// Define o tipo de retorno do método.
methodBuilder.SetReturnType(returnParameter[0]);
}
else {
// Informa ao MethodBuilder os nomes dos tipos genéricos.
methodBuilder.DefineGenericParameters(genericArguments.Select(p => p.Name).ToArray());
}
IEnumerable<Type> orderedParameters = parameters.OrderBy(p => p.Key).Select(p => p.Value);
//.........这里部分代码省略.........
示例13: DictionaryEditorWindow
public DictionaryEditorWindow(Dictionary<string, object> dictionary)
{
Value = dictionary;
Width = 415;
Height = 375;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Text = "Настройки материала";
this.StartPosition = FormStartPosition.CenterScreen;
this.MaximizeBox = false;
this.MinimizeBox = false;
//
list = new TreeView();
list.Parent = this;
list.Width = 150;
list.Height = 300;
list.Left = 0;
list.Top = 0;
list.AfterSelect += list_AfterSelect;
//
grid = new PropertyGrid();
grid.Parent = this;
grid.Width = 250;
grid.Height = 300;
grid.Left = 150;
grid.Top = 0;
grid.PropertySort = PropertySort.NoSort;
grid.ToolbarVisible = false;
//
ok = new Button();
ok.Parent = this;
ok.Width = 100;
ok.Height = 24;
ok.Left = 290;
ok.Top = 305;
ok.Text = "OK";
ok.Visible = true;
ok.Click += ok_Click;
//
for (int i = 0; i < dictionary.Count; i++)
{
KeyValuePair<string, object> val = dictionary.ElementAt(i);
TreeNode node = list.Nodes.Add(val.Key + " (" + val.Value.GetType().Name + ")");
node.Tag = val.Key;
}
}
示例14: LocateMatchingRule
public static RuleMethod LocateMatchingRule(Dictionary<int, List<TokenResult>> buckets, ConversationContext context)
{
var Rules = new List<RuleMethod>();
//check our tokens against the rules
foreach (var rule in CommandRules)
{
//Console.WriteLine(rule.Name + " params:" + rule.GetParameters().Count().ToString());
//get the params of the method
var parameters = (from p in rule.GetParameters()
where p.ParameterType != typeof(ConversationContext)
select p).ToList();
int index = 0;
var parms = new List<TokenResult>();
//for each parm, see if the corresponding bucket has a token of that type
foreach (var parameterInfo in parameters)
{
Type searchType = parameterInfo.ParameterType;
TokenResult token = null;
if (buckets.Count > 0)
{
token = (from t in buckets.ElementAt(index).Value
where
t.Token.GetType() == searchType ||
t.Token.GetType().IsSubclassOf(searchType)
select t).FirstOrDefault();
if (searchType == typeof(TokenWhoWasIn) && token != null)
{
for (int i = index + 1; i < buckets.Count; i++)
{
foreach (var result in buckets.ElementAt(i).Value)
{
if (result.Token is TokenQuotedPhrase)
{
parms.Add(token);
parms.Add(result);
break;
}
}
}
break;
}
}
if (null != token)
{
parms.Add(token);
if (index < buckets.Count - 1)
{
index++;
}
else
{
break;
}
}
else
{
break;
}
}
if (parms.Count == parameters.Count() && parms.Count > 0)
{
var passins = new object[parms.Count + 1];
passins[0] = context;
for (int i = 1; i < parms.Count + 1; i++)
{
passins[i] = parms[i - 1].Token;
}
Rules.Add(new RuleMethod
{
PassIns = passins,
Rule = rule
});
}
}
RuleMethod ruleMethod = Rules.Where(r => r.PassIns.Count() == Rules.Max(s => s.PassIns.Count())).FirstOrDefault();
return ruleMethod;
}
示例15: UpdateScoreInTraineeTopic
public ActionResult UpdateScoreInTraineeTopic(Dictionary<string, object> model)
{
string status = string.Empty;
string message = string.Empty;
var DictraineeID = model.ElementAt(0);
string[] traineeID = (string[])DictraineeID.Value;
// var entity = new Tra_TraineeTopicEntity();
var lstEntity = new List<Tra_TraineeTopicEntity>();
var topicServices = new ActionService(UserLogin);
var objTopic = new List<object>();
objTopic.Add(null);
objTopic.Add(null);
objTopic.Add(null);
objTopic.Add(null);
objTopic.Add(1);
objTopic.Add(int.MaxValue - 1);
var lstTopic = topicServices.GetData<Cat_TopicEntity>(objTopic, ConstantSql.hrm_cat_sp_get_Topic, ref status).ToList();
var traineeScoreServices = new Tra_TraineeScoreServices();
var objTraineeScore = new List<object>();
objTraineeScore.Add(1);
objTraineeScore.Add(int.MaxValue - 1);
var lstTraineeScore = topicServices.GetData<Tra_TraineeScoreEntity>(objTraineeScore, ConstantSql.hrm_tra_sp_get_TraineeScore, ref status).ToList();
var scoreTopicServices = new ActionService(UserLogin);
var objScoreTopic = new List<object>();
objScoreTopic.Add(1);
objScoreTopic.Add(int.MaxValue - 1);
var lstScoreTopic = scoreTopicServices.GetData<Tra_ScoreTopicEntity>(objScoreTopic, ConstantSql.hrm_tra_sp_get_ScoreTopic, ref status).ToList();
var traineeTopicServices = new Tra_TraineeTopicServices();
var objTraineeTopic = new List<object>();
objTraineeTopic.Add(1);
objTraineeTopic.Add(int.MaxValue - 1);
var lstTraineeTopic = topicServices.GetData<Tra_TraineeTopicEntity>(objTraineeTopic, ConstantSql.hrm_tra_sp_get_TraineeTopic, ref status).ToList();
if (model.Count > 0)
{
for (int i = 3; i < model.Count; i++)
{
var entity = new Tra_TraineeTopicEntity();
var item = model.ElementAt(i);
var strTitle = item.Key.Split('_');
string[] score = (string[])item.Value;
var topicEnity = lstTopic.Where(s => item.Key.Contains(s.Code)).FirstOrDefault();
if (topicEnity != null)
{
var scoreTopicEntity = lstScoreTopic.Where(s => topicEnity.ID == s.TopicID && strTitle[1] == s.Code).FirstOrDefault();
var traineeTopicEntity = lstTraineeTopic.Where(s => s.TraineeID != null && topicEnity.ID == s.TopicID && Guid.Parse(traineeID[0]) == s.TraineeID.Value).FirstOrDefault();
if (traineeTopicEntity != null)
{
//Edit cột score trong bảng traineeTopic
if (!string.IsNullOrEmpty(score[0]))
{
traineeTopicEntity.Score = double.Parse(score[0]);
}
else {
traineeTopicEntity.Score = null;
}
message = traineeTopicServices.Edit(traineeTopicEntity);
//Kiểm tra trong bảng TraineeScoree. Nếu chưa có record thì tạo mới nguoc lai thì edit record
var traineeScoreEntity = lstTraineeScore.Where(s => s.TraineeTopicID == traineeTopicEntity.ID && scoreTopicEntity.ScoreTypeID == s.ScoreTypeID).FirstOrDefault();
if (traineeScoreEntity == null)
{
Tra_TraineeScoreEntity newTraineeScoreEntity = new Tra_TraineeScoreEntity();
newTraineeScoreEntity.ScoreTypeID = scoreTopicEntity.ScoreTypeID;
newTraineeScoreEntity.TraineeTopicID = traineeTopicEntity.ID;
newTraineeScoreEntity.Score = traineeTopicEntity.Score;
message = traineeScoreServices.Add(newTraineeScoreEntity);
}
else
{
traineeScoreEntity.Score = traineeTopicEntity.Score;
message = traineeScoreServices.Edit(traineeScoreEntity);
}
// lstEntity.Add(traineeTopicEntity);
}
}
}
//message = traineeTopicServices.Edit(lstEntity);
}
return null;
}