C# Remove line of data from List - c#

Here is my List declaration:
public List<CharactersOnline> charactersOnline = new List<CharactersOnline>();
public class CharactersOnline
{
public int connectionId;
public int characterId;
public string characterName;
}
Here is how i add lines into this list:
charactersOnline.Add(new CharactersOnline() { connectionId = cnnId, characterId = charId, characterName = name });
Here is how i think i can remove one line by just poiting one of the parameters:
private void CharacterLogout(int charId)
{
charactersOnline.Remove(new CharactersOnline() { characterId = charId });
}
Can i remove all the data on the line of the list by just pointing only one of the parameters or this is just going to delete the data for characterId only ?
I need to know how can i delete the whole line of this list.

One way to do that is to find it and then remove it:
var charactersOnline = new List<CharactersOnline>();
var target = charactersOnline.SingleOrDefault(x => x.characterId == 1);
charactersOnline.Remove(target);
So your method will be like this:
private void CharacterLogout(int charId)
{
var target = charactersOnline.SingleOrDefault(x => x.characterId == charId);
charactersOnline.Remove(target);
}

Another approach in more functional way.
private void CharacterLogout(int charId)
{
charactersOnline = charactersOnline.Where(line => line.characterId != charId)
.ToList();
}
Notice, that approach above will remove all lines with given charId value.
Your approach will not work because Remove method will search for element with same reference as given item to remove.
The line new CharactersOnline() { characterId = charId } will create new instance of object which reference not exists in the list.
So for removing correct item you should find it first.
var indexesToRemove =
charactersOnline.Select((line, index) => (Id: line.characterId, Index: index))
.Where(item => item.Id == charId)
.Select(item => item.Index);
foreach (var index in indexesToRemove)
{
charactersOnline.RemoveAt(index);
}

Use this code to remove item from List based on condition
charactersOnline.Remove(charactersOnline.Single(s => s.characterId = charId) );

Related

How to remove duplicates from object list based on that object property in c#

I've got a problem with removing duplicates at runtime from my list of object.
I would like to remove duplicates from my list of object and then set counter=counter+1 of base object.
public class MyObject
{
MyObject(string name)
{
this.counter = 0;
this.name = name;
}
public string name;
public int counter;
}
List<MyObject> objects_list = new List<MyObject>();
objects_list.Add(new MyObject("john"));
objects_list.Add(new MyObject("anna"));
objects_list.Add(new MyObject("john"));
foreach (MyObject my_object in objects_list)
{
foreach (MyObject my_second_object in objects_list)
{
if (my_object.name == my_second_object.name)
{
my_object.counter = my_object.counter + 1;
objects_list.remove(my_second_object);
}
}
}
It return an error, because objects_list is modified at runtime. How can I get this working?
With a help of Linq GroupBy we can combine duplicates in a single group and process it (i.e. return an item which represents all the duplicates):
List<MyObject> objects_list = ...
objects_list = objects_list
.GroupBy(item => item.name)
.Select(group => { // given a group of duplicates we
var item = group.First(); // - take the 1st item
item.counter = group.Sum(g => g.counter); // - update its counter
return item; // - and return it instead of group
})
.ToList();
The other answer seem to be correct, though I think it will do scan of the whole list twice, depending on your requirement this might or might not be good enough. Here is how you can do it in one go:
var dictionary = new Dictionary<string, MyObject>();
foreach(var obj in objects_list)
{
if(!dictionary.ContainsKey(obj.name)
{
dictionary[obj.name] = obj;
obj.counter++;
}
else
{
dictionary[obj.name].counter++;
}
}
Then dictionary.Values will contain your collection

Change my new list without changing the original list

This is my original list:
var cart = _workContext.CurrentCustomer.ShoppingCartItems
.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
.LimitPerStore(_storeContext.CurrentStore.Id)
.ToList();
I reviewed this link : How do I change my new list without changing the original list?
And have understood that I have a method for copy so this is my method:
private List<ShoppingCartItem> CopyShoppingCartItems(List<ShoppingCartItem> target)
{
//var tmp = new List<ShoppingCartItem>(target);
var tmp = target.ToList();
return tmp;
}
I test var var tmp = new List<shoppingCartItem>(target)too.
this is my goal:
var beforeUpdatCart = CopyShoppingCartItems(cart);
foreach (var sci in cart)
{
var remove = allIdsToRemove.Contains(sci.Id);
if (remove)
_shoppingCartService.DeleteShoppingCartItem(sci, ensureOnlyActiveCheckoutAttributes: true);
else
{
foreach (var formKey in form.Keys)
if (formKey.Equals($"itemquantity{sci.Id}", StringComparison.InvariantCultureIgnoreCase))
{
int newQuantity;
if (int.TryParse(form[formKey], out newQuantity))
{
sci.Quantity = newQuantity;
}
break;
}
}
}
but newQuantity is inserted in both List<shoppingCartItem> : cart and beforeUpdateCart.
Can any one help me?
So you're actually changing the item in the list, not inserting the item into the list. While your lists are referencing different objects, they contain references on the same objects. That's why you get the item updated in both. Consider using deep copy to fix your issue. It may be done by creating copying constructor:
public ShoppingCartItem(ShoppingCartItem item)
{
// copy all your fields there
}
And then:
private List<ShoppingCartItem> CopyShoppingCartItems(List<ShoppingCartItem> target)
{
var tmp = target.ConvertAll(i => new ShoppingCartItem(i));
return tmp;
}

How to compare two csv files by 2 columns?

I have 2 csv files
1.csv
spain;russia;japan
italy;russia;france
2.csv
spain;russia;japan
india;iran;pakistan
I read both files and add data to lists
var lst1= File.ReadAllLines("1.csv").ToList();
var lst2= File.ReadAllLines("2.csv").ToList();
Then I find all unique strings from both lists and add it to result lists
var rezList = lst1.Except(lst2).Union(lst2.Except(lst1)).ToList();
rezlist contains this data
[0] = "italy;russia;france"
[1] = "india;iran;pakistan"
At now I want to compare, make except and union by second and third column in all rows.
1.csv
spain;russia;japan
italy;russia;france
2.csv
spain;russia;japan
india;iran;pakistan
I think I need to split all rows by symbol ';' and make all 3 operations (except, distinct and union) but cannot understand how.
rezlist must contains
india;iran;pakistan
I added class
class StringLengthEqualityComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
...
}
public int GetHashCode(string obj)
{
...
}
}
StringLengthEqualityComparer stringLengthComparer = new StringLengthEqualityComparer();
var rezList = lst1.Except(lst2,stringLengthComparer ).Union(lst2.Except(lst1,stringLengthComparer),stringLengthComparer).ToList();
Your question is not very clear: for instance, is india;iran;pakistan the desired result primarily because russia is at element[1]? Isn't it also included because element [2] pakistan does not match france and japan? Even though thats unclear, I assume the desired result comes from either situation.
Then there is this: find all unique string from both lists which changes the nature dramatically. So, I take it that the desired results are because "iran" appears in column[1] no where else in column[1] in either file and even if it did, that row would still be unique due to "pakistan" in col[2].
Also note that a data sample of 2 leaves room for a fair amount of error.
Trying to do it in one step makes it very confusing. Since eliminating dupes found in 1.CSV is pretty easy, do it first:
// parse "1.CSV"
List<string[]> lst1 = File.ReadAllLines(#"C:\Temp\1.csv").
Select(line => line.Split(';')).
ToList();
// parse "2.CSV"
List<string[]> lst2 = File.ReadAllLines(#"C:\Temp\2.csv").
Select(line => line.Split(';')).
ToList();
// extracting once speeds things up in the next step
// and leaves open the possibility of iterating in a method
List<List<string>> tgts = new List<List<string>>();
tgts.Add(lst1.Select(z => z[1]).Distinct().ToList());
tgts.Add(lst1.Select(z => z[2]).Distinct().ToList());
var tmpLst = lst2.Where(x => !tgts[0].Contains(x[1]) ||
!tgts[1].Contains(x[2])).
ToList();
That results in the items which are not in 1.CSV (no matching text in Col[1] nor Col[2]). If that is really all you need, you are done.
Getting unique rows within 2.CSV is trickier because you have to actually count the number of times each Col[1] item occurs to see if it is unique; then repeat for Col[2]. This uses GroupBy:
var unique = tmpLst.
GroupBy(g => g[1], (key, values) =>
new GroupItem(key,
values.ToArray()[0],
values.Count())
).Where(q => q.Count == 1).
GroupBy(g => g.Data[2], (key, values) => new
{
Item = string.Join(";", values.ToArray()[0]),
Count = values.Count()
}
).Where(q => q.Count == 1).Select(s => s.Item).
ToList();
The GroupItem class is trivial:
class GroupItem
{
public string Item { set; get; } // debug aide
public string[] Data { set; get; }
public int Count { set; get; }
public GroupItem(string n, string[] d, int c)
{
Item = n;
Data = d;
Count = c;
}
public override string ToString()
{
return string.Join(";", Data);
}
}
It starts with tmpList, gets the rows with a unique element at [1]. It uses a class for storage since at this point we need the array data for further review.
The second GroupBy acts on those results, this time looking at col[2]. Finally, it selects the joined string data.
Results
Using 50,000 random items in File1 (1.3 MB), 15,000 in File2 (390 kb). There were no naturally occurring unique items, so I manually made 8 unique in 2.CSV and copied 2 of them into 1.CSV. The copies in 1.CSV should eliminate 2 if the 8 unique rows in 2.CSV making the expected result 6 unique rows:
NepalX and ItalyX were the repeats in both files and they correctly eliminated each other.
With each step it is scanning and working with less and less data, which seems to make it pretty fast for 65,000 rows / 130,000 data elements.
your GetHashCode()-Method in EqualityComparer are buggy. Fixed version:
public int GetHashCode(string obj)
{
return obj.Split(';')[1].GetHashCode();
}
now the result are correct:
// one result: "india;iran;pakistan"
btw. "StringLengthEqualityComparer"is not a good name ;-)
private void GetUnion(List<string> lst1, List<string> lst2)
{
List<string> lstUnion = new List<string>();
foreach (string value in lst1)
{
string valueColumn1 = value.Split(';')[0];
string valueColumn2 = value.Split(';')[1];
string valueColumn3 = value.Split(';')[2];
string result = lst2.FirstOrDefault(s => s.Contains(";" + valueColumn2 + ";" + valueColumn3));
if (result != null)
{
if (!lstUnion.Contains(result))
{
lstUnion.Add(result);
}
}
}
}
class Program
{
static void Main(string[] args)
{
var lst1 = File.ReadLines(#"D:\test\1.csv").Select(x => new StringWrapper(x)).ToList();
var lst2 = File.ReadLines(#"D:\test\2.csv").Select(x => new StringWrapper(x));
var set = new HashSet<StringWrapper>(lst1);
set.SymmetricExceptWith(lst2);
foreach (var x in set)
{
Console.WriteLine(x.Value);
}
}
}
struct StringWrapper : IEquatable<StringWrapper>
{
public string Value { get; }
private readonly string _comparand0;
private readonly string _comparand14;
public StringWrapper(string value)
{
Value = value;
var split = value.Split(';');
_comparand0 = split[0];
_comparand14 = split[14];
}
public bool Equals(StringWrapper other)
{
return string.Equals(_comparand0, other._comparand0, StringComparison.OrdinalIgnoreCase)
&& string.Equals(_comparand14, other._comparand14, StringComparison.OrdinalIgnoreCase);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is StringWrapper && Equals((StringWrapper) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((_comparand0 != null ? StringComparer.OrdinalIgnoreCase.GetHashCode(_comparand0) : 0)*397)
^ (_comparand14 != null ? StringComparer.OrdinalIgnoreCase.GetHashCode(_comparand14) : 0);
}
}
}

Elegant way to check if a list contains an object where one property is the same, and replace only if the date of another property is later

I have a class as follows :
Object1{
int id;
DateTime time;
}
I have a list of Object1. I want to cycle through another list of Object1, search for an Object1 with the same ID and replace it in the first list if the time value is later than the time value in the list. If the item is not in the first list, then add it.
I'm sure there is an elegant way to do this, perhaps using linq? :
List<Object1> listOfNewestItems = new List<Object1>();
List<Object1> listToCycleThrough = MethodToReturnList();
foreach(Object1 object in listToCycleThrough){
if(listOfNewestItems.Contains(//object1 with same id as object))
{
//check date, replace if time property is > existing time property
} else {
listOfNewestItems.Add(object)
}
Obviously this is very messy (and that's without even doing the check of properties which is messier again...), is there a cleaner way to do this?
var finalList = list1.Concat(list2)
.GroupBy(x => x.id)
.Select(x => x.OrderByDescending(y=>y.time).First())
.ToList();
here is the full code to test
public class Object1
{
public int id;
public DateTime time;
}
List<Object1> list1 = new List<Object1>()
{
new Object1(){id=1,time=new DateTime(1991,1,1)},
new Object1(){id=2,time=new DateTime(1992,1,1)}
};
List<Object1> list2 = new List<Object1>()
{
new Object1(){id=1,time=new DateTime(2001,1,1)},
new Object1(){id=3,time=new DateTime(1993,1,1)}
};
and OUTPUT:
1 01.01.2001
2 01.01.1992
3 01.01.1993
This is how to check:
foreach(var object in listToCycleThrough)
{
var currentObject = listOfNewestItems
.SingleOrDefault(obj => obj.Id == object.Id);
if(currentObject != null)
{
if (currentObject.Time < object.Time)
currentObject.Time = object.Time
}
else
listOfNewestItems.Add(object)
}
But if you have large data, would be suggested to use Dictionary in newest list, time to look up will be O(1) instead of O(n)
You can use LINQ. Enumerable.Except to get the set difference(the newest), and join to find the newer objects.
var listOfNewestIDs = listOfNewestItems.Select(o => o.id);
var listToCycleIDs = listToCycleThrough.Select(o => o.id);
var newestIDs = listOfNewestIDs.Except(listToCycleIDs);
var newestObjects = from obj in listOfNewestItems
join objID in newestIDs on obj.id equals objID
select obj;
var updateObjects = from newObj in listOfNewestItems
join oldObj in listToCycleThrough on newObj.id equals oldObj.id
where newObj.time > oldObj.time
select new { oldObj, newObj };
foreach (var updObject in updateObjects)
updObject.oldObj.time = updObject.newObj.time;
listToCycleThrough.AddRange(newestObjects);
Note that you need to add using System.Linq;.
Here's a demo: http://ideone.com/2ASli
I'd create a Dictionary to lookup the index for an Id and use that
var newItems = new List<Object1> { ...
IList<Object1> itemsToUpdate = ...
var lookup = itemsToUpdate.
Select((i, o) => new { Key = o.id, Value = i }).
ToDictionary(i => i.Key, i => i.Value);
foreach (var newItem in newitems)
{
if (lookup.ContainsKey(newitem.ID))
{
var i = lookup[newItem.Id];
if (newItem.time > itemsToUpdate[i].time)
{
itemsToUpdate[i] = newItem;
}
}
else
{
itemsToUpdate.Add(newItem)
}
}
That way, you wouldn't need to reenumerate the list for each new item, you'd benefit for the hash lookup performance.
This should work however many times an Id is repeated in the list of new items.

Find the count of duplicate items in a C# List

I am using List in C#. Code is as mentioned below:
TestCase.cs
public class TestCase
{
private string scenarioID;
private string error;
public string ScenarioID
{
get
{
return this.scenarioID;
}
set
{
this.scenarioID = value;
}
}
public string Error
{
get
{
return this.error;
}
set
{
this.error = value;
}
}
public TestCase(string arg_scenarioName, string arg_error)
{
this.ScenarioID = arg_scenarioName;
this.Error = arg_error;
}
}
List I am createing is:
private List<TestCase> GetTestCases()
{
List<TestCase> scenarios = new List<TestCase>();
TestCase scenario1 = new TestCase("Scenario1", string.Empty);
TestCase scenario2 = new TestCase("Scenario2", string.Empty);
TestCase scenario3 = new TestCase("Scenario1", string.Empty);
TestCase scenario4 = new TestCase("Scenario4", string.Empty);
TestCase scenario5 = new TestCase("Scenario1", string.Empty);
TestCase scenario6 = new TestCase("Scenario6", string.Empty);
TestCase scenario7 = new TestCase("Scenario7", string.Empty);
scenarios.Add(scenario1);
scenarios.Add(scenario2);
scenarios.Add(scenario3);
scenarios.Add(scenario4);
scenarios.Add(scenario5);
scenarios.Add(scenario6);
scenarios.Add(scenario7);
return scenarios;
}
Now I am iterating through the list. I want to find the how many duplicate testcases are there in a list with same ScenarioID. Is there any way to solve it using Linq or any inbuilt method for List?
Regards,
Priyank
Try this:
var numberOfTestcasesWithDuplicates =
scenarios.GroupBy(x => x.ScenarioID).Count(x => x.Count() > 1);
As a first idea:
int dupes = list.Count() - list.Distinct(aTestCaseComparer).Count();
To just get the duplicate count:
int duplicateCount = scenarios.GroupBy(x => x.ScenarioID)
.Sum(g => g.Count()-1);
var groups = scenarios.GroupBy(test => test.ScenarioID)
.Where(group => group.Skip(1).Any());
That will give you a group for each ScenarioID that has more than one items. The count of the groups is the number of duplicate groups, and the count of each group internally is the number of duplicates of that single item.
Additional note, the .Skip(1).Any() is there because a .Count() in the Where clause would need to iterate every single item just to find out that there is more than one.
Something like this maybe
var result= GetTestCases()
.GroupBy (x =>x.ScenarioID)
.Select (x =>new{x.Key,nbrof=x.Count ()} );
To get total number of duplicates, yet another:
var set = new HashSet<string>();
var result = scenarios.Count(x => !set.Add(x.ScenarioID));
To get distinct duplicates:
var result = scenarios.GroupBy(x => x.ScenarioID).Count(x => x.Skip(1).Any());

Categories