Click here to Skip to main content
15,886,016 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a list with 8 elements and I want to sort/order only the first 6 elements, and leave the last two as they are?
C#
List<string> lst = new List<string>();
Random rnd = new Random();

for (int i = 0; i < 8; i++)
{
    char let;
    do
    {
        int num = rnd.Next(0, 26);
        let = (char)('A' + num);
    } while (lst.Contains(let.ToString()));

    lst.Add(let.ToString());
}

//I want to sort the first 6 elements here

ListViewItem lvi = new ListViewItem(lst[0]);
for (int i = 1; i < lst.Count; i++)
{
    lvi.SubItems.Add(lst[i]);
}
lvwCheckOut.Items.Add(lvi);

If the letters in the list are: D L A Z R U W G
I want my output to be: A D L R U Z W G

What I have tried:

I have tried a lot of thing, I get the results I want if I do two lists. List 1 with 6 elements and just use "lst1.Sort();" then list 2 with 2 elements and leave it random.
Posted
Updated 12-Jun-16 18:24pm
Comments
Sergey Alexandrovich Kryukov 12-Jun-16 17:14pm    
Are you sure you need exactly that, not something more specific, such as a median filter — in this case, the formulation should be different.
What is the problem with your code? Did you use the debugger?
—SA
Alan N 12-Jun-16 18:13pm    
If would be great if there was a Sort method that allowed a list subrange to be specified. If such a method was to exist, it would be in the documentation for the generic list class. HINT - go and look.
George Jonsson 12-Jun-16 18:58pm    
Very subtle :)

Look here: partial sort - Is there a C# equivalent to C++ std::partial_sort? - Stack Overflow[^].

The second answer (Lee) would allows you to sort only the first 6 items.

See also MSDN documentation: List(T).Sort Method (Int32, Int32, IComparer(T)) (System.Collections.Generic)[^]
 
Share this answer
 
v2
While the solution linked to here by Philippe Mori based (probably) on the suggestion by Alan N. in his comment will, indeed, get the correct result, do you really need to make the solution this complex ?

Why not simply first generate six random letters, and, then, you can easily sort them, and then generate two random letters ?
C#
private static Random randGenerator = new Random(DateTime.Now.Millisecond);

private static string Letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

public IEnumerable<char> GetRandomChars(int count, bool useuppercase = false)
{
    for (int i = 0; i < count; i++)
    {
        yield return
            (useuppercase)
                ? Letters[randGenerator.Next(0, 52)]
                : Letters[randGenerator.Next(0, 26)];
    }
}
// use example: execute in some Method or EventHandler
C#
var firstsix = GetRandomChars(6, false).ToList();
firstsix.Sort();

var lasttwo = GetRandomChars(2, false);

var result = firstsix.Concat(lasttwo);
Note:

1. this code goes back many years to pre-Linq days, and was updated, after the first version of Linq came along, to return an IEnumerable result for convenience.

2. note that you have to "evaluate to an actual result" the IEnumerable contained in the var 'firstsix before you can call the 'Sort operator, and note that 'Sort transforms its argument but returns nothing (i.e., 'void).

3. The final var 'result will contain an IEnumerable<char>, so keep in mind that "deferred evaluation" is in effect here; that's something I recently tried to explain here: [^].

4. note the 'Sort operator used here is not Linq; it's a method provided by System.Collections.Generic, which arrived with C#2.0
 
Share this answer
 
try this

C#
var first6Sorted = lst.Take(6).OrderBy(k => k).ToList();  // First 6 chars sorted
    var last2UnSorted = lst.Skip(6).ToList(); // last 2 chars unsorted
    lst = first6Sorted;
    lst.AddRange(last2UnSorted);  // merging both the collection
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900