Menu
  • HOME
  • TAGS

C# IEnumerable and string[]

Tag: c#,arrays,string,split,ienumerable

i searched for a method to split strings and i found one.
Now my problem is that i can´t use the method like it is described.

Stackoverflow answer

It is going to tell that i

cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string[]'.

The provided method is:

public static class EnumerableEx
{
    public static IEnumerable<string> SplitBy(this string str, int chunkLength)
    {
        if (String.IsNullOrEmpty(str)) throw new ArgumentException();
        if (chunkLength < 1) throw new ArgumentException();

        for (int i = 0; i < str.Length; i += chunkLength)
        {
            if (chunkLength + i > str.Length)
                chunkLength = str.Length - i;

            yield return str.Substring(i, chunkLength);
        }
    }
}

How he said it is used:

string[] result = "bobjoecat".SplitBy(3); // [bob, joe, cat]

Best How To :

You have to use ToArray() method:

string[] result = "bobjoecat".SplitBy(3).ToArray(); // [bob, joe, cat]

You can implicitly convert Array to IEnumerable but cannot do it vice versa.

while Inherit style in WPF it affect parent style

c#,xaml,styles,wpf-controls

If you declare a Style without an x:Key, it will override the default style for that control. <Style TargetType="local:CustomControl"> So the code above will effect all CustomControl elements throughout the entire application (or within the scope). If you do not want to override the base style, you can give your...

How to return result while applying Command query separation (CQS)

c#,design-patterns,cqrs,command-query-separation

In such scenario I usually go with generating new entity Ids on the client. Like this: public class ProductController: Controller{ private IProductCommandService commandService; private IProductQueryService queryService; private IIdGenerationService idGenerator; [HttpPost] public ActionResult Create(Product product){ var newProductId = idGenerator.NewId(); product.Id = newProductId; commandService.AddProduct(product); //TODO: add url parameter or TempData key to...

Regex that allow void fractional part of number

c#,regex

Just get the dot outside of the captruing group and then make it as optional. @"[+-]?\d+\.?\d*" Use anchors if necessary. @"^[+-]?\d+\.?\d*$" ...

check if file is image

c#,asp.net,asp.net-mvc

You can't do this: string.Contains(string array) Instead you have to rewrite that line of code to this: if (file == null || formats.Any(f => file.Contains(f))) And this can be shortened down to: if (file == null || formats.Any(file.Contains)) ...

Aligning StackPanel to top-center in Canvas

c#,wpf,xaml,canvas

If you don't want any input or hit testing on a certain element you should set the IsHitTestVisible property to false: <Grid> <Canvas Name="Canvas" Background="#EFECCA"> <DockPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Width="{Binding ActualWidth, ElementName=Canvas}" Height="{Binding ActualHeight, ElementName=Canvas}" MouseLeftButtonDown="DockPanel_MouseLeftButtonDown" TouchDown="DockPanel_TouchDown" Panel.ZIndex="2" Background="Transparent"> </DockPanel> <Button Width="50" Height="50"...

C# XML: System.InvalidOperationException

c#,xml

Is "User Info" and "Course Data" is a different entity. If it is so, I think you may encapsulate them in one entity. XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8); writer.WriteStartDocument(true); writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.WriteStartElement("My Entity"); /* It is a biggest one*/ writer.WriteStartElement("User Info"); writer.WriteStartElement("Name"); writer.WriteString(userName); writer.WriteEndElement(); writer.WriteStartElement("Tutor...

How do I provide a collection of elements to a custom attached property?

c#,wpf,binding

I managed to get it working using an IMultiValueConverter like this: public class BorderCollectionConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var borderCollection = new BorderCollection(); borderCollection.AddRange(values.OfType<Border>()); return borderCollection; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new...

how can I add a column to IQueryable object and modify its values

c#,.net,linq,grid,devexpress

Simple example for using a non-anonymous class. public class MyLovelyClass { public Int32 Number { get; set; } public bool Selection { get; set; } } var packs = from r in new XPQuery<Roll>(session) select new MyLovelyClass() { Number = r.number }; gcPack.DataSource = packs; ...

Update list of items in c#

c#,linq,list,updates

I would do something like this: (for ordinairy lists) // the current list var currentList = new List<Employee>(); currentList.Add(new Employee { Id = 154, Name = "George", Salary = 10000 }); currentList.Add(new Employee { Id = 233, Name = "Alice", Salary = 10000 }); // new list var newList =...

Index was out of range. Must be non-negative or less than size of collection [duplicate]

c#

It looks like you have a typo in your loop condition: for (int index = filePaths.Count(); filePaths.Count() > 9; index--) It should be for (int index = filePaths.Count() - 1; index > 9; index--) Also note that for the first iteration of loop you're trying to access filePaths[filePaths.Count()] which is...

Blank screen on GridView

android,arrays,gridview

I executed ur code. Just add numberView.setTextColor(Color.BLACK); and it will work! :)...

Why is the task is not cancelled when I call CancellationTokenSource's Cancel method in async method?

c#,asynchronous,task,cancellationtokensource,cancellation-token

Cancellation in .Net is cooperative. That means that the one holding the CancellationTokenSource signals cancellation and the one holding the CancellationToken needs to check whether cancellation was signaled (either by polling the CancellationToken or by registering a delegate to run when it is signaled). In your Task.Run you use the...

How to send Ctrl+S through SendKeys.Send() method to save a file(save as dialog)

c#,.net,windows,sendkeys

I believe you need to use: SendKeys.SendWait("^(s)"); Instead of: SendKeys.SendWait("^%s?"); Have a look at https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send(v=vs.110).aspx for more information....

System.net.http.formatting causing issues with Newtonsoft.json

c#,asp.net,asp.net-mvc,json.net

Does the assemblyBinding tag have proper xmlns schema? Check if the issue you are encountering is same as Assembly binding redirect does not work

Collect strings after a foreach loop

c#,xml,foreach

Yep, you need to do the adding within the loop. I'd use a List<string> as it supports LINQ: XmlNodeList skillNameNodeList=SkillXML.GetElementsByTagName("name"); List<string> skills = new List<string>(); foreach (XmlNode skillNameNode in skillNameNodeList) { skills.Add(skillNameNode.Attributes["value"].Value); } ...

Convert contents of an XmlNodeList to a new XmlDocument without looping

c#,xml,xpath,xmldocument,xmlnodelist

If you're happy to convert it into LINQ to XML, it's really simple: XDocument original = ...; // However you load the original document // Separated out for clarity - could be inlined, of course string xpath = "//Person[not(PersonID = following::Person/PersonID)]" XDocument people = new XDocument( new XElement("Persons", original.XPathSelectElements(xpath) )...

Visual Studio Assembly force-installs Target Framework

c#,.net,visual-studio-2013,.net-framework-version

The targeted .NET version is the only version that the app will depend upon by default. Visual Studio will not automatically add higher and backwards compatible releases. Do this manually by adding other .NET versions to a configuration file: On the Visual Studio menu bar: Choose Project; Add New Item;...

Javascript function to validate contents of an array

javascript,arrays

You can use a simple array based test like var validCodes = ['IT00', 'O144', '6A1L', '4243', 'O3D5', '44SG', 'CE64', '54FS', '4422']; function validItems(items) { for (var i = 0; i < items.length; i++) { if (validCodes.indexOf(items[i]) == -1) { return items[i]; } } return ''; } var items = ["IT00",...

Infinite loop with fread

c,arrays,loops,malloc,fread

If you're "trying to allocate an array 64 bytes in size", you may consider uint8_t Buffer[64]; instead of uint8_t *Buffer[64]; (the latter is an array of 64 pointers to byte) After doing this, you will have no need in malloc as your structure with a 64 bytes array inside is...

Convert Date Time to IST

c#

You need to use "India Standard Time" instead of "Indian". Please refer to this link for a list of the time zone descriptions.

array and function php

php,arrays

$x and $y are only defined within the scope of the function. The code outside of the function does not know what $x or $y are and therefore will not print them. Simply declare them outside of the function as well, like so: <?php function sum($x, $y) { $z =...

Foreign key in C#

c#,sql,sql-server,database

You want create relationship in two table Refer this link http://www.c-sharpcorner.com/Blogs/5608/create-a-relationship-between-two-dataset-tables.aspx...

Substring of a file

javascript,arrays,substring

To get your desired output, this will do the trick: var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d"; var array = file.split(", ") // Break up the original string on `", "` .map(function(element, index){ var temp = element.split('|'); return [temp[0], temp[1], index + 1]; }); console.log(array); alert(JSON.stringify(array)); The split converts...

C# Code design / Seperate classes for each TabControl

c#,oop,architecture,software-design,code-design

Place a UserControl on each tab.

Get object by attribute value [duplicate]

c#,reflection,custom-attributes,spring.net

If you have obtained the Assembly, you can just iterate over the types and check for your conditions: var matchingTypes = from t in asm.GetTypes() where !t.IsInterface && !t.IsAbstract where typeof(ICustomInterface).IsAssignableFrom(t) let foo = t.GetCustomAttribute<FooAttribute>() where foo != null && foo.Bar == Y select t; I am assuming you want...

Is it possible to concactenate a DataBound value with a constant string in XAML DataBinding?

c#,xaml,windows-phone

You can use a StringFormat in your binding, like so: <TextBox Text="{Binding ItemName, StringFormat={}Item: {0}}"/> That being said, it may cause some unexpected behavior when editing. For example, if the user edits only the item name (excluding the 'Item:' text), then when the TextBox loses focus, the string format will...

deployment of a site asp.net and iis

c#,asp.net,iis

There are several domain providers like: godaddy, name etc you can use to buy a domain name. These providers also provide you steps to map the domain name to your website. Check out this link for example. This link explains domain name configuration in details.

Get elements containing text from array

javascript,jquery,html,arrays,contains

You can use :contains selector. I think you meant either one of those values, in that case var arr = ['bat', 'ball']; var selectors = arr.map(function(val) { return ':contains(' + val + ')' }); var $lis = $('ul li').filter(selectors.join()); $lis.css('color', 'red') <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li>...

Marshal struct in struct from c# to c++

c#,c++,marshalling

Change this: [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] private string iu; to this: [MarshalAs(UnmanagedType.LPStr)] private string iu; Note that this code is good only to pass a string in the C#->C++ direction. For the opposite direction (C++->C#) it is more complex, because C# can't easily deallocate C++ allocated memory. Other important thing:...

Translating a character array into a integer string in C++

c++,arrays,string

If you want a sequence of int, then use a vector<int>. Using the key_char string, the values of the chars in it will serve as the initial value of the ints. std::vector<int> key_num(key_char.begin(), key_char.end()); Then, iterate over each character of key_num and convert it to the equivalent int value for...

Difference between application and module pipelines in Nancy?

c#,asp.net,nancy

The module- and application pipelines are explained in detail in the wiki. It's basically hooks which are executed before and after route execution on a global (application pipelines) and per-module basis. Here's an example: If a route is resolved to a module called FooModule, the pipelines will be invoked as...

Multiple Threads searching on same folder at same time

c#,multithreading,file-search

Instead of using ordinary foreach statement in doing your search, you should use parallel linq. Parallel linq combines the simplicity and readability of LINQ syntax with the power of parallel programming. Just like code that targets the Task Parallel Library. This will shield you from low level thread manipulation and...

C# PCL HMACSHAX with BouncyCastle-PCL

c#,bouncycastle,portable-class-library

Try like this for HmacSha256 public class HmacSha256 { private readonly HMac _hmac; public HmacSha256(byte[] key) { _hmac = new HMac(new Sha256Digest()); _hmac.Init(new KeyParameter(key)); } public byte[] ComputeHash(byte[] value) { if (value == null) throw new ArgumentNullException("value"); byte[] resBuf = new byte[_hmac.GetMacSize()]; _hmac.BlockUpdate(value, 0, value.Length); _hmac.DoFinal(resBuf, 0); return resBuf; }...

Create array from another with specific indices

javascript,arrays

You can use .map, like so var data = [ 'h', 'e', 'l', 'l', 'o', ' ' ]; var indices = [ 4, 0, 5, 0, 1, 2, 2 ]; var res = indices.map(function (el) { return data[el]; }); console.log(res); The map() method creates a new array with the results...

How to declare var datatype in public scope in c#?

c#,linq

Declare it as a known type (not an anonymous type), like this for example: Dictionary<int, string> results = new Dictionary<int, string>(); Then you could store the results in the Dictionary: results = behzad.GAPERTitles.ToDictionary(x => x.id, x => x.gaptitle); And reference it later: private void button1_Click(object sender, EventArgs e) { //...

Regex to remove `.` from a sub-string enclosed in square brackets

c#,.net,regex,string,replace

To remove all the dots present inside the square brackets. Regex.Replace(str, @"\.(?=[^\[\]]*\])", ""); DEMO To remove dot or ?. Regex.Replace(str, @"[.?](?=[^\[\]]*\])", ""); ...

Javascript sort array of objects in reverse chronological order

javascript,arrays,sorting

As PM 77-1 suggests, consider using the built–in Array.prototype.sort with Date objects. Presumably you want to sort them on one of start or end: jobs.sort(function(a, b) { return new Date(a.ys, a.ms-1) - new Date(b.ys, b.ms-1); }) ...

Ruby: How to copy the multidimensional array in new array?

ruby-on-rails,arrays,ruby,multidimensional-array

dup does not create a deep copy, it copies only the outermost object. From that docs: Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. If you are not sure how deep your object...

How to pivot array into another array in Ruby

arrays,ruby,csv

Here is a way using an intermediate hash-of-hash The h ends up looking like this {"Alaska"=>{"Rain"=>"3", "Snow"=>"4"}, "Alabama"=>{"Snow"=>"2", "Hail"=>"1"}} myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] myFields = ["Snow","Rain","Hail"] h = Hash.new{|h, k| h[k] = {}} myArray.each{|i, j, k| h[i][j] = k } p [["State"] + myFields] + h.map{|k, v| [k] + v.values_at(*myFields)} output...

Access manager information from Active Directory

c#,asp.net,active-directory

try this: var loginName = @"loginNameOfInterestedUser"; var ldap = new DirectoryEntry("LDAP://domain.something.com"); var search = new DirectorySearcher(ldap) { Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + loginName + "))" }; var result = search.FindOne(); if (result == null) return; var fullQuery = result.Path; var user = new DirectoryEntry(fullQuery); DirectoryEntry manager; if (user.Properties.PropertyNames.OfType<string>().Contains("manager")) { var managerPath...

Memory consumption when chaining string methods

c#,string,immutability,method-chaining

Is it true that when you chain string functions, every function instantiates a new string? In general, yes. Every function that returns a modified string does so by creating a new string object that contains the full new string which is stored separately from the original string. There are...

Merge and sum values and put them in an array

javascript,arrays,angularjs,foreach

You cannot store key-value pair in array. Use object to store key-value pair. See comments inline in the code. var obj = {}; // Initialize the object angular.forEach(data, function(value, key) { if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) { if (obj[value.firstname]) { // If already exists obj[value.firstname] += value.distance;...

Catch concurrency exception in EF6 to change message to be more user friendly

c#,asp.net,.net,entity-framework,entity-framework-6

You are executing an asynchronous method. This means that any exceptions will be thrown when you call await on the returned task or when you try to retrieve the results using await myTask; You never do so, which means that the exception is thrown and caught higher up your call...

How to innerHTML a function with array as parameter?

javascript,arrays,loops,foreach,innerhtml

Just take a variable for the occurrence of even or odd numbers. var myArray = function (nums) { var average = 0; var totalSum = 0; var hasEven = false; // flag if at least one value is even => true, otherwise false nums.forEach(function (value) { totalSum = totalSum +...

How to Customize Visual Studio Setup

c#,visual-studio,setup-project

You can use a Microsoft Setup project or WIX (easily integrate with Visual Studio). Both are free. •You can do almost all of your customization in setup project by adding custom actions. •WIX (window installer xml) is the better option. You can do a complete customization from wix but it...

Validate a field only if it is populated

c#,wpf,idataerrorinfo

You can implement your OptionalPhoneAttribute based on the original PhoneAttribute: public sealed class OptionalPhoneAttribute : ValidationAttribute { public override bool IsValid(object value) { var phone = new PhoneAttribute(); //return true when the value is null or empty //return original IsValid value only when value is not null or empty return...

How can I determine if an object of anonymous type is empty?

c#,.net

Anonymous types do not provide operator overloads for ==, although it wouldn't matter in this case since one of the arguments is typed object. However the C# compiler does provide Equals, GetHashCode, and ToString implementations. Use the static object.Equals, method which will do the appropriate null checks and then call...

pointer to pointer dynamic array in C++

c++,arrays,pointers

The valid range of indices of an array with N elements is [0, N-1]. Thus instead of for example this loop for (int i=1; i <= n; i++) ^^^^ ^^^^^^ you have to write for ( int i = 0; i < n; i++ ) As you used operator new...

SQL Server / C# : Filter for System.Date - results only entries at 00:00:00

c#,asp.net,sql-server,date,gridview-sorting

What happens if you change all of the filters to use 'LIKE': if (DropDownList1.SelectedValue.ToString().Equals("Start")) { FilterExpression = string.Format("Start LIKE '{0}%'", TextBox1.Text); } Then, you're not matching against an exact date (at midnight), but matching any date-times which start with that date. Update Or perhaps you could try this... if (DropDownList1.SelectedValue.ToString().Equals("Start"))...

Load XML to list using LINQ [duplicate]

c#,xml,linq

Make a base class which will have id,x,y,z, and have Vendors,Bankers and Hospitals extend it. Then you can have a collection of the base class, and add to it the classes that inherit from it....