how to replace values in list in C#? - c#

I have a list:
List<string> strlist=new List<string>();
strlist.add("UK");
strlist.add("US");
strlist.add("India");
strlist.add("Australia");
I want to change the index of some elements in the list:
The current index of "US" is 1, I want to replace it with 3 and for "Australia" it should be 1.

If you know the indices already, you can just use 'swap' them:
var temp = strlist[1];
strlist[1] = strlist[3];
strlist[3] = temp;

It seems to me that you really just want to sort the list.
If so, just do this:
strlist.Sort().
This will work for a plain list of strings, because string defines a suitable comparison operator that Sort() can use.
If you want to keep "UK" at the start of the list and sort the rest of the list, you can do so like this:
strlist.Sort(1, strlist.Count-1, null);
The above line will result in the list being:
UK
Australia
India
US

Try this:
Use a swapping variable
String app = strlist[1];
strlist[1] = strlist[3];
strlist[3] = app;

List<string> can be indexed using list[index] = .... That if you want to replace items manually. Otherwise (I'm guessing), if you need to sort the list alphabetically, but leave the "UK" at the top then you need to do sorting:
var list = new List<string> {"UK", "US", "India", "Australia" };
list.Sort((a, b) =>
{
if (a == "UK")
return -1;
if (b == "UK")
return 1;
return string.Compare(a, b, StringComparison.CurrentCulture);
});

Related

Can I sort a List<string> by integers inside of them?

For example;
List<string> list = new List<string>{
"1[EMPTY]", "2[EMPTY]", "3[EMPTY]", "4[EMPTY]", "5[EMPTY]", "6[EMPTY]", "7[EMPTY]", "8[EMPTY]", "9[EMPTY]", "10[EMPTY]", "11[EMPTY]", "12[EMPTY]"
};
When I use
list.Sort();
Output:
1[EMPTY] 10[EMPTY] 11[EMPTY] 12[EMPTY] 2[EMPTY] 3[EMPTY] 4[EMPTY] 5[EMPTY] 6[EMPTY] 7[EMPTY] 8[EMPTY] 9[EMPTY]
I want 1-2-3-4-5-6-7-8-9-10-11-12.
How can i solve this problem?
(Sorry my English is bad :{)
You can use OrderBy. Basically trick is to sort the string so parsing as int. and getting the value till the first occurance of [.
List<string> list = new List<string>{
"1[EMPTY]", "2[EMPTY]", "3[EMPTY]", "4[EMPTY]", "5[EMPTY]", "6[EMPTY]", "7[EMPTY]", "8[EMPTY]", "9[EMPTY]", "10[EMPTY]", "11[EMPTY]", "12[EMPTY]"
};
list = list.OrderBy(c => int.Parse(c.Substring(0, c.IndexOf('[')))).ToList();

c# remove everything in List collection after a particular index

I want to be able to remove all elements in a List<string> after a certain index
List<string> s_array= new List<string>();
s_array.Add("a");
s_array.Add("x");
s_array.Add("c");
s_array.Add("y");
s_array.Add("e");
s_array.Add("e");
s_array.RemoveAll(/* what goes here?*/);
What can i put in RemoveAll to achieve this? for example say i wanted to cut out everything from c onwards?
Not sure what all your parameters are, so it's hard to say what approach will be best.
Using RemoveAll(), you could do:
s_array.RemoveAll(x => s_array.IndexOf(x) > s_array.IndexOf("c"));
You could use the key words Take or Skip to help - Example:
var s_array = new List<string> {"a","x","c","y","e","e" };
var sorted = (from x in s_array orderby x select x);
var first3 = sorted.Take(3);
var last2 = sorted.Take(2).Skip(5);

A Linq ContainsAll Method?

I have a list of items that can each have multiple keywords so I have three tables
Item -> ItemKeyword <- Keyword
I want to return all Items where the Item has all keywords in a list. so for example:
Item 1 has keywords "Rabbit", "Dog", "Cat"
Item 2 has keywords "Rabbit", Hedgehog", "Dog"
I want to return only those items that have both "Dog" and "Cat" as keywords.
I cant use a contains query as that will essentially return all those items with "Dog" OR "Cat".
So I guess what I am asking for is if there is such a thing called ContainsAll in linq, or if there is some way I can perform this functionality.
I have attempted to use Except and Intersect but I cant seem to get the correct results.
I would like to have a single query so that it is easy to compile the query but this is not a dealbreaker.
I am using:
Dot Net 4.5
Visual Studio 2012
C#
Linq
Entity Framework
Sql Server Ce 4.0
I cant use a contains query as that will essentially return all those items with "Dog" OR "Cat".
This is simply not true. You can use two contains with an AND && :
items.Where(item => item.Keywords.Contains("Dog") && item.Keywords.Contains("Cat"));
Or you can put the values you are looking for in an array then use All method to make it shorter:
var values = new [] { "Dog", "Cat" };
items.Where(item => values.All(item.Keywords.Contains));
Please check this .. code is written lengthier for better understanding .. Assuming each item as an identifier to check
List<item> ItemsList = new List<item>();
item item1 = new item();
item1.ID = "1";
item1.keywords = new List<string>();
item1.keywords.Add("Rabbit");
item1.keywords.Add("Dog");
item1.keywords.Add("Cat");
ItemsList.Add(item1);
item item2 = new item();
item2.ID = "2";
item2.keywords = new List<string>();
item2.keywords.Add("Rabbit");
item2.keywords.Add("Hedgehog");
item2.keywords.Add("Dog");
ItemsList.Add(item2);
//this the list you want to check
var values = new List<string> ();
values.Add("Dog");
values.Add("Cat");
var result = from x in ItemsList
where !(values.Except(x.keywords).Any())
select x;
foreach (var item in result)
{
// Check the item.ID;
}

Searching a list of strings in C#

So I want to use one of these LINQ functions with this List<string> I have.
Here's the setup:
List<string> all = FillList();
string temp = "something";
string found;
int index;
I want to find the string in all that matches temp when both are lower cased with ToLower(). Then I'll use the found string to find it's index and remove it from the list.
How can I do this with LINQ?
I get the feeling that you don't care so much about comparing the lowercase versions as you do about just performing a case-insensitive match. If so:
var listEntry = all.Where(entry =>
string.Equals(entry, temp, StringComparison.CurrentCultureIgnoreCase))
.FirstOrDefault();
if (listEntry != null) all.Remove(listEntry);
OK, I see my imperative solution is not getting any love, so here is a LINQ solution that is probably less efficient, but still avoids searching through the list two times (which is a problem in the accepted answer):
var all = new List<string>(new [] { "aaa", "BBB", "Something", "ccc" });
const string temp = "something";
var found = all
.Select((element, index) => new {element, index})
.FirstOrDefault(pair => StringComparer.InvariantCultureIgnoreCase.Equals(temp, pair.element));
if (found != null)
all.RemoveAt(found.index);
You could also do this (which is probably more performant than the above, since it does not create new object for each element):
var index = all
.TakeWhile(element => !StringComparer.InvariantCultureIgnoreCase.Equals(temp, element))
.Count();
if (index < all.Count)
all.RemoveAt(index);
I want to add to previous answers... why don't you just do it like this :
string temp = "something";
List<string> all = FillList().Where(x => x.ToLower() != temp.ToLower());
Then you have the list without those items in the first place.
all.Remove(all.FirstOrDefault(
s => s.Equals(temp,StringComparison.InvariantCultureIgnoreCase)));
Use the tool best suited for the job. In this case a simple piece of procedural code seems more appropriate than LINQ:
var all = new List<string>(new [] { "aaa", "BBB", "Something", "ccc" });
const string temp = "something";
var cmp = StringComparer.InvariantCultureIgnoreCase; // Or another comparer of you choosing.
for (int index = 0; index < all.Count; ++index) {
string found = all[index];
if (cmp.Equals(temp, found)) {
all.RemoveAt(index);
// Do whatever is it you want to do with 'found'.
break;
}
}
This is probably as fast as you can get, because:
Comparison it done in place - there is no creation of temporary uppercase (or lowercase) strings just for comparison purposes.
Element is searched only once (O(index)).
Element is removed in place without constructing a new list (O(all.Count-index)).
No delegates are used.
Straight for tends to be faster than foreach.
It can also be adapted fairly easily should you want to handle duplicates.

How to reverse the order of displaying content of a list?

Let's say I have a list of integers.
var myList = new List<int>();
1, 2, 3, 4, 5, ..., 10
Is there any function that allows me to display them in reverse order, i.e.
10, 9, 8, ..., 1
EDIT
public List<Location> SetHierarchyOfLocation(Location location)
{
var list = new List<Location>(7);
var juridiction = location.Juridiction;
if (juridiction > 0)
{
while (juridiction > 0)
{
var loc = repository.GetLocationByID(juridiction);
list.Add(loc);
juridiction = loc.Juridiction;
}
}
return list;
}
Since the list contains location by location, I want to be able to display it by reversed order as well.
Now, when I write return list.Reversed(), I get the error.
Thanks for helping
var reversed = myList.Reverse() should do the trick.
EDIT:
Correction- as the OP found out, List.Reverse works in-place, unlike Enumerable.Reverse. Thus, the answer is simply myList.Reverse(); - you don't assign it to a new variable.
Is there any function that allows me to display them in reverse order, i.e.
It depends if you want to reverse them in place, or merely produce a sequence of values that is the reverse of the underlying sequence without altering the list in place.
If the former, just use List<T>.Reverse.
// myList is List<int>
myList.Reverse();
Console.WriteLine(String.Join(", ", myList));
If the latter, the key is Enumerable.Reverse:
// myList is List<int>
Console.WriteLine(
String.Join(
", ",
myList.AsEnumerable().Reverse()
)
);
for a beautiful one-liner. Be sure you have using System.Linq;.
To do a foreach loop in a List<Location> reversely you should use:
foreach (Location item in myList.Reverse().ToList())
{
// do something ...
}
The .Reverse() is an in-place reverse; it doesn't return a new list. The .ToList() after the .Reverse() do the trick.

Categories

Resources