Insatantiate Generic Collection with Initial Values?

You know how you can instantiate an array of, say, strings and specify
intial values at the same time with something like:

string[] myStrings = new string[3] { "value1", "value2", "value3" };

Can the same type of thing be done for a List<string> object?

I've done a lot of web searching but I can't find any sample code that
illustrates this.
0
Joe
1/22/2010 8:41:54 PM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

5 Replies
671 Views

Similar Articles

[PageSpeed] 7

Joe Cool wrote:
> You know how you can instantiate an array of, say, strings and specify
> intial values at the same time with something like:
> 
> string[] myStrings = new string[3] { "value1", "value2", "value3" };
> 
> Can the same type of thing be done for a List<string> object?
> 
> I've done a lot of web searching but I can't find any sample code that
> illustrates this.

Not literally like that, no.

But, note that List<T> has a constructor overload that takes an 
IEnumerable<T> as an argument.  So you can do this:

   List<string> myStrings = new List<string>(new string[] { "value1", 
"value2", "value3" });

Pete
0
Peter
1/22/2010 9:03:03 PM
Peter Duniho wrote:
> Not literally like that, no.
>
> But, note that List<T> has a constructor overload that takes an 
> IEnumerable<T> as an argument.  So you can do this:
>
>   List<string> myStrings = new List<string>(new string[] { "value1", 
> "value2", "value3" });
>
> Pete

Is there a reason to not use:
List<string> myStrings = new List<string>
                                         {
                                             "value1",
                                             "value2"
                                         };

Seems to compile fine on VS2008 on a .NET 3.5 app.

-Adam
0
Adam
1/22/2010 10:34:39 PM
On 2010-01-22, Joe Cool <joecool1969@live.com> wrote:
> You know how you can instantiate an array of, say, strings and specify
> intial values at the same time with something like:
>
> string[] myStrings = new string[3] { "value1", "value2", "value3" };
>
> Can the same type of thing be done for a List<string> object?
>
> I've done a lot of web searching but I can't find any sample code that
> illustrates this.

Yes - if your using vs2008 (C# 3.0):

List<string> strs = new List<string>() {"value1", "value2", "value3"};

you can do it with dictionary type classes as well:

Dictionary<int, string> dict = new Dictionary<int, string>() { {1, "Hi"}, {2, "Bye"}};

Look up collection initializers...

-- 
Tom Shelton
0
Tom
1/22/2010 10:38:27 PM
Adam Clauss wrote:
> Peter Duniho wrote:
>> Not literally like that, no.
>>
>> But, note that List<T> has a constructor overload that takes an 
>> IEnumerable<T> as an argument.  So you can do this:
>>
>>   List<string> myStrings = new List<string>(new string[] { "value1", 
>> "value2", "value3" });
>>
>> Pete
> 
> Is there a reason to not use:
> List<string> myStrings = new List<string>
>                                         {
>                                             "value1",
>                                             "value2"
>                                         };
> 
> Seems to compile fine on VS2008 on a .NET 3.5 app.

No, I guess not.  Believe it or not, I never realized that the 
collection initializer syntax works with things other than arrays.  In 
hindsight, that was silly of me; there's a reason they called that 
"collection initializer" and not "array initializer".  :)

Either way, the same constructor gets called.  The newer syntax seems 
nicer to me though.

Pete
0
Peter
1/23/2010 12:44:35 AM
Peter Duniho wrote:
> [...]
> Either way, the same constructor gets called.  The newer syntax seems 
> nicer to me though.

Oops.  I take that back.  The newer syntax may be nicer, but now that 
I've spent a little time bringing myself up-to-date on the topic, I see 
that the older syntax can be significantly more efficient.

The newer syntax doesn't use the constructor taking an IEnumerable<T>, 
but instead generates a series of explicit calls to the Add() method for 
the collection class.  (Actually, this seems vaguely familiar to me�I 
think I knew about this new feature at one point, and just forgot).

On the plus side, this is a more general-purpose approach that can be 
applied to any collection type with an Add() method.  But on the minus 
side, it can result in a pretty bloated method and lots of extra 
execution overhead.  For a collection with just a small number of 
elements, that may not matter much (and frankly, the initializer syntax 
usually ought to be reserved for such situations), but for a large data 
set, the more explicit approach can be much more efficient.

Pete
0
Peter
1/23/2010 2:32:18 AM
Reply:

Similar Artilces:

Overlapping of values in different tables.
I am wondering if there is a way to create a pivot table - or some other way - that will show the relationships of rows between tables. I have attached data from potentially 4 different tables and the business is wanting to see the number of times that a paticular ID shows up in different table join combinations. For example, we want to know the count of unique IDs will show in the NPS, AAC and ECM tables. Is it possible to create a pivot table that will dynamically adjust based on a user choosing the column combinations that they want to see without having to create a separate pivot...

Collecting data from Excel form
I am working in Excel 2003 and would like to know if there is a way to create a form for data fill-in so that the data would then be collected in a database elsewhere. Thank you, Ricki Ricki, You can go to http://smartusemicrosoftoffice.blogspot.com/2010/03/linking-data-from-form-to-database.html to see it is the solution you want. Hope can help me. Thanks for the post. his is the task I would like to accomplish, but there are no instructions on how to accomplish this task., just a screen shot on what will happen. Where can I find the instructions to get this to work?...

find location max value in column
I need to find the cell location of the max value in a column. If paste the following [from =(cell onwards] into a cell I get the righ result. Having a hgard time getting the right VBA code to make thi work in an unattended macro. Probably some bonehead mistake on my part but I cannot find it. Suggestions? GOAL is to make this formula work. Range("z2").Formula "=(CELL(e1,OFFSET(e1,MATCH(MAX(e1:e100),e1:100,0)-1,0)))" TIA, Ro -- rroac ----------------------------------------------------------------------- rroach's Profile: http://www.excelforum.com/member.php?act...

Retrieving default values specified from XML Schema file
Hi All, I have an VS.NET 2003 app which will be processing XML files, some of which will have empty elements (for example, <Item />). I have an XSD file which should supply default values, but I am not able to read these plugged in value using an XMLDocument object. The validation is working fine--it's just not providing any default values. Has anybody tried this? Am I must be missing something? This is one of those that "should be simple..." Here's a simplifed version of the code and XML files: XmlDocument xmldoc = new XmlDocument(); XmlSchemaCollection my...

multi-value field
I'm still learning Access, so I must apologize in advance for my question. I have four tables, tblBrochure, tblStaff, tblOrganization, tblResourceDistribution. tblBrochure has two fields -BrochureName -Active (y/n) tblStaff has two fields -StaffName -Active (y/n) tblOrganization has two fields -OrgName -textbox (0 and 1, explained below) tblResourceDistribution has 5 fields -DistribDate -StaffName (lookup from tblStaff ->Staffname -Organization (lookup from tblOrganization ->OrgName) ...

Problem with draging a formula,one cell value fixed,trivial question
Hi. I have a value in cell A10. Then i have a formula in cell C1 which goes: (A1+B1)/A10. If I drag the formula down to cell C5 the formula for C2 will be (A2+B2)/A11, for C3 will be (A3+B3)/A12,....,for C5 will be (A5+B)/A14. I would like the formula to have the A10 parameter fixed so when i drag the formula down the A10 would always be A10(it wouldn't go up by 1). So the formula for C2 will be (A2+B2)/A10, for C3 will be (A3+B3)/A10,....,for C5 will be (A5+B5)/A10. Please help. Thanks, Marko make your original in C1 formula =(A1+B1)/A$10 then drag down. See help on absolute versus re...

Lookup value selection
Is there any way to select lookup value by pressing "Enter" key on keyboard and avoid mouse click? -- romeo!! Please clarify. I could use the up and down arrow to select the values and then press "Enter" key to select the lookup value - works for me in v4.0. Frank Lee, Microsoft Dynamics CRM MVP http://www.workopia.com/Links.htm http://microsoft-crm.spaces.live.com "romeo" wrote: > Is there any way to select lookup value by pressing "Enter" key on keyboard > and avoid mouse click? > > -- > romeo!! ...

Vlookup
Dear all, For vlookup, it will return the value of the destination cell. Is it possible to return the row no. instead of value of the destination cell?? Your help is highly appreciated. Thanks & regards, Automne Look at the MATCH function in Help. On Sat, 5 Mar 2005 01:41:39 +0800, "automne" <hersbt_no_spam@yahoo.com.hk> wrote: >Dear all, > >For vlookup, it will return the value of the destination cell. Is it >possible to return the row no. instead of value of the destination cell?? > >Your help is highly appreciated. > >Thanks & regards,...

How to ignore records with a duplicate ID based on a value
I hae searched the forum tono avail, so I'll ask for help. I have a table [Scope Event Table] which records events with status changes. The table uses an auto numbered primary key (not shown in the example below). It has data like this: DR_ID Event_Date Reason 12556 01/03/2008 Added 12556 01/24/2008 Closed 12874 01/05/2008 Added 14128 02/09/2008 Added I am a novice at SQL. I am trying to build a query that would pull only the DR_ID’s where the most recent Reason = “Added”. So I would want results to look like this: DR_ID Event_Date Reason 12874 01/05/2008 Added 14128 02/09/2008...

merging a value in a text field with each line in a memo field
I am trying to merge a value in a text field with the information in a memo field using a query to create a report. This is the query I am using: SELECT AVRelay+","+IPRange FROM T_Sites AVRelay is the text field and IPRange is the Memo. IPRange has multiple lines, each of which I need appended with the value in AVRelay for the report. It should look like. 2,192.168.1.0/24 2,192.168.0.0/24 2,192.168.2.0/24 Instead it looks like 2,192.168.1.0/24 192.168.0.0/24 192.168.2.0/24 I have searched far and wide but has come up empty. Please help! I would gues...

Set default values
I've set up a template where I have headers and cell validations. I want to be able to have some of the fileds in the row autopopulate once the first cell in the row is entered. Do you know of a way that I can code this using VBA. For example, A3 is populated with a value, I then want G3 to be updated with a "1". -- Message posted via http://www.officekb.com In G3: =IF(A3="","",1) -- Gary''s Student - gsnu2007k In G3 use the formula =IF(A3<>"",1,"") The "" is a pair of double-quotes with no space between be...

Sending value to a cell
Hi there, I want to dump a computed value into a cell that isn't the one the calculation was done in. Can it be done from the original cell? Hi no, not with a formula -- Regards Frank Kabel Frankfurt, Germany "CM32134" <CM32134@discussions.microsoft.com> schrieb im Newsbeitrag news:0768C79B-586C-42CB-A7AE-1A817C4CE5F5@microsoft.com... > Hi there, > I want to dump a computed value into a cell that isn't the one the > calculation was done in. Can it be done from the original cell? A worksheet formula returns a value and can do nothing else. Think...

I am making a charts with weird X-values for my Ecology cl\
i am making a chart with weird X-values. Instead of single, whole numbers, I need each value to be as follows: 1-2, 3-5, 6-10, 11-15, etc. Please help me!! My chart keeps going to whole numbers instead and its been driving me crazy for days! What chart type are you using? If you want your X-axis to be category labels, rather than actual numbers, you may find that a line chart (or one of the other chart types) is more suitable than an XY (scatter) chart, if the latter is what you are currently trying. -- David Biddulph "Holly" <Holly@discussions.microsoft.com> wro...

Exchange 2k7 powershell truncates multi-value properties
Greetings, I'm running the following command: Get-SendConnector -Identity "Send Connector Name" | ft -autosize -wrap -property AddressSpaces We have over 20 domains in this list. When I run this command it lists 16 of these domains and then just sticks ... at the end. If I leave out the -wrap switch the output lists only 3 domains. How can I get this command to list ALL the contents of the AddressSpaces property? Thanks Try to pipe to format-list instead. --- Shay Levy Windows PowerShell MVP http://blogs.microsoft.co.il/blogs/ScriptFanatic...

Crystal XI will not show all possible values in a parameter field
Hello: We have a Crystal XI report that has one parameter value that is a "static" rather than "dynamic". It works fine and, when you type in a value upon refreshing the report, the data is correct. We made a copy of the report, because we want a second report where the parameter value is dynamic rather than static. We do not want a range, but we do want a parameter that will show all possible values on the left and allow you to pick and choose one or more of those values. For some reason, not all of the possible values are showing in this dynamic parameter field...

How to round the numeric value?
Kindly tell me that how can we round the numeric value? Example: 1.2 = 1.5, 1.7 = 2.0 "Salman Saeed" <Salman Saeed@discussions.microsoft.com> wrote in message news:F5460D85-6DEE-4EC5-8E83-A1A5E158966A@microsoft.com... > Kindly tell me that how can we round the numeric value? > Example: 1.2 = 1.5, 1.7 = 2.0 Use the RND function..... =CEILING(A1,0.5) -- Regards Dave Hawley www.ozgrid.com "Salman Saeed" <Salman Saeed@discussions.microsoft.com> wrote in message news:F5460D85-6DEE-4EC5-8E83-A1A5E158966A@microsoft.com... > Kindly...

vlookup-Closest value
Dear Friends, How can I use Vlookup to give me the closest value greather than or equal to vlookup value.For example if my lookup value is 5 and I have 4.9 and 5.1,5.2 It chooses 5.1 and give me the corresponding value. Thank you, atatari wrote: > Dear Friends, > > How can I use Vlookup to give me the closest value greather than or equal to > vlookup value.For example if my lookup value is 5 and I have 4.9 and 5.1,5.2 > It chooses 5.1 and give me the corresponding value. > > Thank you, VLOOKUP(lookup_value,table_array,col_index_num,range_lookup) The default behavi...

The most occurence of a value in a column
I have 1 to 5 as values in a column. How can I find the number with the most occurrence in that column? Thanks, cpliu Hi =MODE(A1:A100) -- Regards Frank Kabel Frankfurt, Germany "cpliu" <chanciusliuDeleteThis@yahoo.com> schrieb im Newsbeitrag news:Xns959C8C47C309BchanciusliuDeleteThi@130.133.1.4... > I have 1 to 5 as values in a column. How can I find the number with the > most occurrence in that column? > > Thanks, > > cpliu Try: =INDEX(A1:A5,MATCH(MAX(COUNTIF(A1:A5,A1:A5)),COUNTIF (A1:A5,A1:A5),0)) Array-entered, meaning press ctrl/shift/enter. H...

isv.config rollback to default value when publish new customization
dear expert, Anybody had idea for this problem?? "msnews.microsoft.com" <hattha9@hotmail.com> wrote in message news:eSkdJp7UFHA.3312@TK2MSFTNGP09.phx.gbl... > dear expert, > Anybody had idea for this problem?? > > > Yes, there is another copy of the ISV.config that gets copied on public - cant remember where it is. A search will find it, rename it and all will be fine for the next publish. I will try and find the exact location and post The file should be located in the c:\Program Files\Microsoft CRM\Tools\Config, or wherever you installed M...

reformulating question regarding maximum value
I had an hour ago put a question up named "find maximum", but I had not formulated my query fully, hence this query. In each row, I want to find the second highest value in that row, and then as output give the value of that cell in the first row. For example: 1 2 6 8 6 5 4 3 2 4 5 6 3 2 3 8 6 4 5 3 7 2 3 1 The second largest value in the second row is nr 6. It is in the fourht cell of that row. The fourth cell of the first row is the value 8. This should be the output for the second row. The second largest value in the third row is the number 6. It is in the first cell of th...

Automatic formatting of minimum/maximum value in a range.
I want that if I select a range of numbers the minimum or maximum should be selected by a single command How about cond. formatting? 1. Select the range. 2. Go to Format > Conditional Formatting 3. Select "Formula Is" and copy in this: =OR(INDIRECT("rc",0)=MAX(rng),INDIRECT("rc",0)=MIN(rng)) where "rng" is a defined name for your range. HTH Jason Atlanta, GA >-----Original Message----- >I want that if I select a range of numbers the minimum or maximum should be >selected by a single command >. > What do you want to do with t...

Creating array from matrix with blank values
I have a matrix in the following format 1 X X X X X X X X X X X 3 X X X X X 4 X X X X X X X X where 'X' is a blank cell. I need to get the data in the form 1 3 4 Any suggestions? I tried a nested if statement but it doesn't work since there are more than 7 ifs. Andryll, If there is only one value in each row, then simply using =SUM(A1:L1) where A1:L1 is your top row, then copied down for two more rows, will give you your desired result. HTH, Bernie MS Excel MVP <Andryll.Davis@gmail.com> wrote in message news:1160141392.644344.173360@i3g2000cwc.googlegroups.com......

Check for values that are not integer
How can I query a column to check for values that have a decimal value. I want to change the data type of a column in a table but I 1st want to confirm there are no values like 3.24 or any other decimal value. thanks in advance, bob On Aug 27, 9:08=A0pm, "Bob McClellan" <bob...@tricolift.RemoveThis.com> wrote: > How can I query a column to check for values > that have a decimal value. > I want to change the data type of a column > in a table but I 1st want to confirm there are no values > like 3.24 or any other decimal value. > > thanks ...

Make values stay put in established record & reset in new record?
I'm having a problem making the values on a form reset to $0.00 when I go to a new record. Some more info would help us to help you. How are you going to a new record? A button you put on the form? the new record button on the navigation buttons at bottom left of form? What does the value show instead of $0.00 when you go to a new record? Are there any other values that don't reset when you go to a new record? Jeanette Cunningham "Peg" <Peg@discussions.microsoft.com> wrote in message news:B39F82B9-43E2-4B9A-8F9B-C64B46240857@microsoft.com... > I'm having a...

Setting Chart X and Y values indirectly
I would like to set X-Values in my chart in a cell of a worksheet, so that when the range of my x-values changes I will not have to go into the wizard and type it again. For example, I want to use the following X-values in my chart: =DATA!$I$2:$I$20 But instead of typing the above in the X Values: field in the 'Source Data / Series' wizard, I would like to type it, say, in cell $A$1 of 'Sheet1', and then type in the X Values field in the 'Source Data / Series' wizard the following: =Sheet1!$A$1 I tried it and it does not work. Can you please let me know if th...