Search Results

Search found 46 results on 2 pages for 'todictionary'.

Page 1/2 | 1 2  | Next Page >

  • Problem in converting ToDictionary<Datetime,double>() using LINQ(C#3.0)

    - by Newbie
    I have written the below return (from p in returnObject.Portfolios.ToList() from childData in p.ChildData.ToList() from retuns in p.Returns.ToList() select new Dictionary<DateTime, double> () { p.EndDate, retuns.Value } ).ToDictionary<DateTime,double>(); Getting error No overload for method 'Add' takes '1' arguments Where I am making the mistake I am using C#3.0 Thanks

    Read the article

  • Problem in converting ToDictionary<Datetime,double>() usinh LINQ(C#3.0)

    - by Newbie
    I have written the below return (from p in returnObject.Portfolios.ToList() from childData in p.ChildData.ToList() from retuns in p.Returns.ToList() select new Dictionary<DateTime, double> () {p.EndDate, retuns.Value }).ToDictionary<DateTime,double>(); Getting error No overload for method 'Add' takes '1' arguments Where I am making the mistake I am using C#3.0 Thanks

    Read the article

  • C# ToDictionary can valueSelector give null?

    - by Trimack
    Hi, I want to make a dictionary out of list in a way, that the list becomes keys and values would be empty. I have following code Dictionary<XmlTest, int?> testBattery = new XmlTests().GetRandomTestBattery(id). ToDictionary(k => k, v => null); But I am getting the error "Cannot convert lambda expression to type System.Collections.Generic.IEqualityComparer' because it is not a delegate type" Any ideas how could I fix it? (I know I could iterate through and fill the dict one element at a time, but I simply want to use something more elegant)

    Read the article

  • C# convert an IOrderedEnumerable<KeyValuePair<string, int>> into a Dictionary<string, int>

    - by Kache4
    I was following the answer to another question, and I got: // itemCounter is a Dictionary<string, int>, and I only want to keep // key/value pairs with the top maxAllowed values if (itemCounter.Count > maxAllowed) { IEnumerable<KeyValuePair<string, int>> sortedDict = from entry in itemCounter orderby entry.Value descending select entry; sortedDict = sortedDict.Take(maxAllowed); itemCounter = sortedDict.ToDictionary<string, int>(/* what do I do here? */); } Visual Studio's asking for a parameter Func<string, int> keySelector. I tried following a few semi-relevant examples I've found online and put in k => k.Key, but that gives a compiler error: 'System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,int>>' does not contain a definition for 'ToDictionary' and the best extension method overload 'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>)' has some invalid arguments

    Read the article

  • C# Custom Dictionary Take - Convert Back From IEnumerable

    - by Goober
    Scenario Having already read a post on this on the same site, which didn't work, I'm feeling a bit stumped but I'm sure I've done this before. I have a Dictionary. I want to take the first 200 values from the Dictionary. CODE Dictionary<int,SomeObject> oldDict = new Dictionary<int,SomeObject>(); //oldDict gets populated somewhere else. Dictionary<int,SomeObject> newDict = new Dictionary<int,SomeObject>(); newDict = oldDict.Take(200).ToDictionary(); OBVIOUSLY, the take returns an IENumerable, so you have to run ToDictionary() to convert it back to a dictionary of the same type. HOWEVER, it just doesn't work, it wants some random key selector thing - or something? I have even tried just casting it but to no avail. Any ideas?

    Read the article

  • Convert IDictionary to Dictionary

    - by croisharp
    I have to convert System.Collections.Generic.IDictionary<string, decimal> to System.Collections.Generic.Dictionary<string, decimal>, and i can't. I tried the ToDictionary method and can't specify right arguments. I've tried the following: // my dictionary is PlannedSurfaces (of type IDictionary<string, decimal>) blabla.ToDictionary<string, decimal>(localConstruction.PlannedSurfaces)

    Read the article

  • Dictionary<string,string> to Dictionary<Control,object> using IEnumerable<T>.Select()

    - by abatishchev
    I have a System.Collections.Generic.Dictionary<string, string> containing control ID and appropriate data column to data bind: var dic = new Dictionary<string, string> { { "Label1", "FooCount" }, { "Label2", "BarCount" } }; I use it that way: var row = ((DataRowView)FormView1.DataItem).Row; Dictionary<Control, object> newOne = dic.ToDictionary( k => FormView1.FindControl(k.Key)), k => row[k.Value]); So I'm using IEnumerable<T>.ToDictionary(Func<T>, Func<T>). Is it possbile to do the same using IEnumerable<T>.Select(Func<T>) ?

    Read the article

  • Parallel EntityFramework

    - by mehanik
    Is it possible to make some work in parallel with entity framework for following example? using (var dbContext = new DB()) { var res = (from c in dbContext.Customers orderby c.Name select new { c.Id, c.Name, c.Role } ).ToDictionary(c => c.Id, c => new Dictionary<string, object> { { "Name",c.Name }, { "Role", c.Role } }); } For exampe what will be changed if I add AsParrallel? using (var dbContext = new DB()) { var res = (from c in dbContext.Customers orderby c.Name select new { c.Id, c.Name, c.Role } ).AsParallel().ToDictionary(c => c.Id, c => new Dictionary<string, object> { { "Name",c.Name }, { "Role", c.Role } }); }

    Read the article

  • Write file at a specific value and line

    - by user2828891
    I want to write data at a specified value in a text file from a text box. Here is a example: item_begin etcitem 3344 item_type=etcitem is first line and item_begin weapon 3343 item_type=weapon is second. Well i want to replace item_type=weapon at second line with item_type=armor. Here is code so far: var data2 = File.WriteAllLines("itemdata.txt") .Where(x => x.Contains("3343")) .Take(1) .SelectMany(x => x.Split('\t')) .Select(x => x.Split('=')) .Where(x => x.Length > 1) .ToDictionary(x => x[0].Trim(), x => x[1]); But returns error at WriteAllLines. Here is the readline part code: var data = File.ReadLines("itemdata.txt") .Where(x => x.Contains("3343")) .Take(1) .SelectMany(x => x.Split('\t')) .Select(x => x.Split('=')) .Where(x => x.Length > 1) .ToDictionary(x => x[0].Trim(), x => x[1]); //call values textitem_type.Text = data["item_type"]; And want to write the same value I change on textitem_type.Text after read. I used this to reaplace but replaces all values with same name from line and returns me in text only 1 line. Code: private void button2_Click(object sender, EventArgs e) { var data = File .ReadLines("itemdata.txt") .Where(x => x.Contains(itemSrchtxt.Text)) .Take(1) .SelectMany(x => x.Split('\t')) .Select(x => x.Split('=')) .Where(x => x.Length > 1) .ToDictionary(x => x[0].Trim(), x => x[1]); StreamReader reader = new StreamReader(Directory.GetCurrentDirectory() + @"\itemdata.txt"); string content = reader.ReadLine(); reader.Close(); content = Regex.Replace(content, data["item_type"], textitem_type.Text); StreamWriter write = new StreamWriter(Directory.GetCurrentDirectory() + @"\itemdata.txt"); write.WriteLine(content); write.Close(); }

    Read the article

  • asp.net mvc custom model binder

    - by mike
    pleas help guys, my custom model binder which has been working perfectly has starting giving me errors details below An item with the same key has already been added. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: An item with the same key has already been added. Source Error: Line 31: { Line 32: string key = bindingContext.ModelName; Line 33: var doc = base.BindModel(controllerContext, bindingContext) as Document; Line 34: Line 35: // DoBasicValidation(bindingContext, doc); Source File: C:\Users\Bich Vu\Documents\Visual Studio 2008\Projects\PitchPortal\PitchPortal.Web\Binders\DocumentModelBinder.cs Line: 33 Stack Trace: [ArgumentException: An item with the same key has already been added.] System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +51 System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) +7462172 System.Linq.Enumerable.ToDictionary(IEnumerable1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer1 comparer) +270 System.Linq.Enumerable.ToDictionary(IEnumerable1 source, Func2 keySelector, IEqualityComparer1 comparer) +102 System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +157 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +158 System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +90 System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +50 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1048 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +280 PitchPortal.Web.Binders.documentModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) in C:\Users\Bich Vu\Documents\Visual Studio 2008\Projects\PitchPortal\PitchPortal.Web\Binders\DocumentModelBinder.cs:33 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +257 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +109 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +314 System.Web.Mvc.Controller.ExecuteCore() +105 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +39 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7 System.Web.Mvc.<c_DisplayClass8.b_4() +34 System.Web.Mvc.Async.<c_DisplayClass1.b_0() +21 System.Web.Mvc.Async.<c_DisplayClass81.b_7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult1.End() +59 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +44 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +7 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8677678 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 any ideas guys? Thanks

    Read the article

  • asp.net mvc custom model binder

    - by mike
    pleas help guys, my custom model binder which has been working perfectly has starting giving me errors details below An item with the same key has already been added. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: An item with the same key has already been added. Source Error: Line 31: { Line 32: string key = bindingContext.ModelName; Line 33: var doc = base.BindModel(controllerContext, bindingContext) as Document; Line 34: Line 35: // DoBasicValidation(bindingContext, doc); Source File: C:\Users\Bich Vu\Documents\Visual Studio 2008\Projects\PitchPortal\PitchPortal.Web\Binders\DocumentModelBinder.cs Line: 33 Stack Trace: [ArgumentException: An item with the same key has already been added.] System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +51 System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) +7462172 System.Linq.Enumerable.ToDictionary(IEnumerable1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer1 comparer) +270 System.Linq.Enumerable.ToDictionary(IEnumerable1 source, Func2 keySelector, IEqualityComparer1 comparer) +102 System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +157 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +158 System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +90 System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +50 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1048 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +280 PitchPortal.Web.Binders.documentModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) in C:\Users\Bich Vu\Documents\Visual Studio 2008\Projects\PitchPortal\PitchPortal.Web\Binders\DocumentModelBinder.cs:33 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +257 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +109 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +314 System.Web.Mvc.Controller.ExecuteCore() +105 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +39 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7 System.Web.Mvc.<c_DisplayClass8.b_4() +34 System.Web.Mvc.Async.<c_DisplayClass1.b_0() +21 System.Web.Mvc.Async.<c__DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult1.End() +59 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +44 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +7 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8677678 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 any ideas guys? Thanks

    Read the article

  • How to Get Dictionary<int, string> from Linq to XML Anonymous Object?

    - by DaveDev
    Currently I'm getting a list of HeaderColumns from the following XML snippet: <HeaderColumns> <column performanceId="12" text="Over last month %" /> <column performanceId="13" text="Over last 3 months %" /> <column performanceId="16" text="1 Year %" /> <column performanceId="18" text="3 Years % p.a." /> <column performanceId="20" text="5 Years % p.a." /> <column performanceId="22" text="10 Years % p.a." /> </HeaderColumns> from which I create an object as follows: (admitedly similar to an earlier question!) var performancePanels = new { Panels = (from panel in doc.Elements("PerformancePanel") select new { HeaderColumns = (from column in panel.Elements("HeaderColumns").Elements("column") select new { PerformanceId = (int)column.Attribute("performanceId"), Text = (string)column.Attribute("text") }).ToList(), }).ToList() }; I'd like if HeaderColumns was a Dictionary() so later I extract the values from the anonymous object like follows: Dictionary<int, string> myHeaders = new Dictionary<int, string>(); foreach (var column in performancePanels.Panels[0].HeaderColumns) { myHeaders.Add(column.PerformanceId, column.Text); } I thought I could achieve this with the Linq to XML with something similar to this HeaderColumns = (from column in panel.Elements("HeaderColumns").Elements("column") select new Dictionary<int, string>() { (int)column.Attribute("performanceId"), (string)column.Attribute("text") }).ToDictionary<int,string>(), but this doesn't work because ToDictionary() needs a Func parameter and I don't know what that is / how to implement it, and the code's probably wrong anyway! Could somebody please suggest how I can achieve the result I need? Thanks.

    Read the article

  • LINQ to XML - How to get Dictionary from Anonymous Object?

    - by DaveDev
    Currently I'm getting a list of HeaderColumns from the following XML snippet: <PerformancePanel> <HeaderColumns> <column performanceId="12" text="Over last month %" /> <column performanceId="13" text="Over last 3 months %" /> <column performanceId="16" text="1 Year %" /> <column performanceId="18" text="3 Years % p.a." /> <column performanceId="20" text="5 Years % p.a." /> <column performanceId="22" text="10 Years % p.a." /> </HeaderColumns> </PerformancePanel> from which I create an object as follows: (admitedly similar to an earlier question!) var performancePanels = new { Panels = (from panel in doc.Elements("PerformancePanel") select new { HeaderColumns = (from column in panel.Elements("HeaderColumns").Elements("column") select new { PerformanceId = (int)column.Attribute("performanceId"), Text = (string)column.Attribute("text") }).ToList(), }).ToList() }; I'd like if HeaderColumns was a Dictionary() so later I extract the values from the anonymous object like follows: Dictionary<int, string> myHeaders = new Dictionary<int, string>(); foreach (var column in performancePanels.Panels[0].HeaderColumns) { myHeaders.Add(column.PerformanceId, column.Text); } I thought I could achieve this with the Linq to XML with something similar to this HeaderColumns = (from column in panel.Elements("HeaderColumns").Elements("column") select new Dictionary<int, string>() { (int)column.Attribute("performanceId"), (string)column.Attribute("text") }).ToDictionary<int,string>(), but this doesn't work because ToDictionary() needs a Func parameter and I don't know what that is / how to implement it, and the code's probably wrong anyway! Could somebody please suggest how I can achieve the result I need? Thanks.

    Read the article

  • C#/.NET Little Wonders: A Redux

    - by James Michael Hare
    I gave my Little Wonders presentation to the Topeka Dot Net Users' Group today, so re-posting the links to all the previous posts for them. The Presentation: C#/.NET Little Wonders: A Presentation The Original Trilogy: C#/.NET Five Little Wonders (part 1) C#/.NET Five More Little Wonders (part 2) C#/.NET Five Final Little Wonders (part 3) The Subsequent Sequels: C#/.NET Little Wonders: ToDictionary() and ToList() C#/.NET Little Wonders: DateTime is Packed With Goodies C#/.NET Little Wonders: Fun With Enum Methods C#/.NET Little Wonders: Cross-Calling Constructors C#/.NET Little Wonders: Constraining Generics With Where Clause C#/.NET Little Wonders: Comparer<T>.Default C#/.NET Little Wonders: The Useful (But Overlooked) Sets The Concurrent Wonders: C#/.NET Little Wonders: The Concurrent Collections (1 of 3) - ConcurrentQueue and ConcurrentStack C#/.NET Little Wonders: The Concurrent Collections (2 of 3) - ConcurrentDictionary Tweet   Technorati Tags: .NET,C#,Little Wonders

    Read the article

  • asp.net MVC binding specific model results in error for post request

    - by Tomh
    Hi I'm having the following two actions defined in my controller [Authorize] [HttpGet] public ActionResult Edit() { ViewData.Model = HttpContext.User.Identity; return View(); } [Authorize] [HttpPost] public ActionResult Edit(User model) { return View(); } However if I post my editted data to the second action I get the following error: Server Error in '/' Application. An item with the same key has already been added. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: An item with the same key has already been added. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. I tried several things like renaming parameters and removing editable fields, but it seems the model type is the problem, what could be wrong? Stack Trace: [ArgumentException: An item with the same key has already been added.] System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +51 System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +7464444 System.Linq.Enumerable.ToDictionary(IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer) +270 System.Linq.Enumerable.ToDictionary(IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer) +102 System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +157 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +158 System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +90 System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +50 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1048 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +280 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +257 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +109 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +314 System.Web.Mvc.Controller.ExecuteCore() +105 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +39 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +34 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +59 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +44 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +7 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8679150 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

    Read the article

  • Casting functions -- Is it a code smell?

    - by Earlz
    I recently began to start using functions to make casting easier on my fingers for one instance I had something like this ((Dictionary<string,string>)value).Add(foo); and converted it to a tiny little helper function so I can do this ToDictionary(value).Add(foo); Is this a code smell? (also I've marked this language agnostic even though my example is C#)

    Read the article

  • Getting Dictionary<string,string> from List<Control>

    - by codymanix
    I want a dictionary containing the names and text of all controls. Is it possible with predefined framework methods/LINQ/colection initializers or do I have to make a loop and add all entries by myself? This gives me an error message: List<Control> controls; // .. initialize list .. controls.ToDictionary((Control child,string k)=>new KeyValuePair<string,string>(child.Name, child.Text));

    Read the article

  • Best way to translate from IDictionary to a generic IDictionary

    - by George Mauer
    I've got an IDictionary field that I would like to expose via a property of type IDictionary<string, dynamic> the conversion is surprisingly difficult since I have no idea what I can .Cast<>() the IDictionary to. Best I've got: IDictionary properties; protected virtual IDictionary<string, dynamic> Properties { get { return _properties.Keys.Cast<string>() .ToDictionary(name=>name, name=> _properties[name] as dynamic); } }

    Read the article

  • How to convert a 2-d array into a dictionary object

    - by Nikron
    Hi, I have an array of type string that looks like this: "test1|True,test2|False,test3|False,test4|True". This is essentially a 2d array like so [test1][True] [test2][False] [test3][False] [test4][True]. I want to convert this into a dictionary<string,bool> using linq, something like: Dictionary<string, bool> myResults = results.Split(",".ToCharArray).ToDictionary() any ideas?

    Read the article

  • How to get XML into a Dictionary with an Expression?

    - by DaveDev
    I have the following XML: <PerformancePanel page="PerformancePanel.ascx" title=""> <FundGroup heading="Net Life Managed Funds"> <fund id="17" countryid="N0" index="24103723" /> <fund id="81" countryid="N0" index="24103723" /> <fund id="127" countryid="N0" index="24103722" /> <fund id="345" countryid="N0" index="24103723" /> <fund id="346" countryid="N0" index="24103723" /> </FundGroup> <FundGroup heading="Net Life Specialist Funds"> <fund id="110" countryid="N0" index="24103717" /> <fund id="150" countryid="N0" index="24103719" /> <fund id="119" countryid="N0" index="24103720" /> <fund id="115" countryid="N0" index="24103727" /> <fund id="141" countryid="N0" index="24103711" /> <fund id="137" countryid="N0" /> <fund id="146" countryid="N0" /> <fund id="133" countryid="N0" /> <fund id="90" countryid="N0" /> <fund id="104" countryid="N0" /> <fund id="96" countryid="N0" /> </FundGroup> </PerformancePanel> I can get the data into an anonymous object as follows: var offlineFactsheet = new { PerformancePanels = (from panel in doc.Elements("PerformancePanel") select new PerformancePanel { PerformanceFunds = (from fg in panel.Elements("FundGroup") select new { Heading = (fg.Attribute("heading") == null) ? "" : (string)fg.Attribute("heading"), Funds = (from fund in fg.Elements("fund") select new Fund { FundId = (int)fund.Attribute("id"), CountryId = (string)fund.Attribute("countryid"), FundIndex = (fund.Attribute("index") == null) ? null : new Index { Id = (int)fund.Attribute("index") }, FundNameAppend = (fund.Attribute("append") == null) ? "" : (string)fund.Attribute("append") }).ToList() }).ToDictionary(xx => xx.Heading, xx => xx.Funds)}; I'm trying to change my code such that I can assign the dictionary directly to a property of the class I'm working in, as described in this question. I'd like to have a Dictionary() where each header text is the key to the list of funds under it. I'm having difficulty applying the example in the linked question because that only returns a string, and this needs to return the dictionary. This is the point that I got to before it occurred to me that I'm lost!!!: this.PerformancePanels = doc.Elements("PerformancePanel").Select(e => { var control = (PerformancePanel)LoadControl(this.OfflineFactsheetPath + (string)e.Attribute("page")); control.PerformanceFunds = e.Elements("FundGroup").Select(f => { List<Fund> funds = (from fund in e.Elements("fund") select new Fund { FundId = (int)fund.Attribute("id"), CountryId = (string)fund.Attribute("countryid"), FundIndex = (fund.Attribute("index") == null) ? null : new Index { Id = (int)fund.Attribute("index") }, FundNameAppend = (fund.Attribute("append") == null) ? "" : (string)fund.Attribute("append") }).ToList(); string heading = (e.Attribute("heading") == null) ? "" : (string)e.Attribute("heading"); }).ToDictionary(xx => heading, xx => Funds); return control; }).ToList(); Could someone point me in the right direction please? I'm not even sure if 'Expression' is the right terminology. Could someone fill me in on that too? Thanks.

    Read the article

  • How to merge two didctionaries in C# with duplicates

    - by user320587
    Hi, Is there a way in C# to merge two dictionaries? I have two dictionaries that may has the same keys, but I am looking for a way to merge them so, in the end there is a dictionary with one key and the values from both the dictionaries merged. I found the following code but it does not handle duplicates. Dictionary Mydictionary<string, string[]> = new Dictionary<string, string[]>(); Mydictonary.Union(secondDictionary).ToDictionary( pair => pair.Key, pair => pair.Value);

    Read the article

  • Problem in populating a dictionary using Enumerable.Range()

    - by Newbie
    If I do for (int i = 0; i < appSettings.Count; i++) { string key = appSettings.Keys[i]; euFileDictionary.Add(key, appSettings[i]); } It is working fine. When I am trying the same thing using Enumerable.Range(0, appSettings.Count).Select(i => { string Key = appSettings.Keys[i]; string Value = appSettings[i]; euFileDictionary.Add(Key, Value); }).ToDictionary<string,string>(); I am getting a compile time error The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly. Any idea? Using C#3.0 Thanks

    Read the article

  • transform List<XElement> to List<XElement.Value>

    - by Miau
    I have a result of a xlinq that is an enumerable with id and phones, I want to transform that to a Dictionary, that part is simple, however the part of transforming the phone numbers from a XElement to a string its proving hard xLinqQuery.ToDictionary(e => e.id, e => e.phones.ToList()); will return Dictionary<int, List<XElement>> what i want is a Dictionary<int, List<String>> I tried with e.phones.ToList().ForEach(...) some strange SelectMany, etc ot no avail Thanks

    Read the article

  • Helper Casting Functions -- Is it a code smell?

    - by Earlz
    I recently began to start using functions to make casting easier on my fingers for one instance I had something like this ((Dictionary<string,string>)value).Add(foo); and converted it to a tiny little helper function so I can do this ToDictionary(value).Add(foo); Is this a code smell? Also, what about simpler examples? For example in my scripting engine I've considered making things like this ((StringVariable)arg).Value="foo"; be ToStringVar(arg).Value="foo"; I really just dislike how inorder to cast a value and instantly get a property from it you must enclose it in double parentheses. I have a feeling the last one is much worse than the first one though (also I've marked this language agnostic even though my example is C#)

    Read the article

  • how to join a set of XElements to the values of a struct?

    - by jcollum
    Let's say I have a struct that contains local environments: public struct Environments { public const string Dev = "DEV"; public const string Qa1 = "SQA"; public const string Prod1 = "PROD"; public const string Prod2 = "PROD_SA"; public const string Uat = "UAT"; } And I'd like to pull a set of XElements out of an xml doc, but only those elements that have a key that matches a value in a struct. this.environments =(from e in settings.Element("Settings").Element("Environments") .Elements("Environment") .Where( x => x.HasAttribute("name") ) join f in [struct?] on e.Attribute("name") equals [struct value?]).ToDictionary(...) How would I go about doing this? Do I need reflection to get the values of the constants in the struct?

    Read the article

1 2  | Next Page >