c# - how can i count duplicates in a list and change the item value -
i have program generates 3 lists based on contents of text file. want @ list , if there's item in more once, i'd change value "number in list x item" , remove duplicates list.
here code use open , split file lists:
private void open_click(object sender, eventargs e) { if (inputfile.showdialog() == dialogresult.ok) { var reader = new streamreader(file.openread(inputfile.filename)); while (!reader.endofstream) { string line = reader.readline(); if (string.isnullorempty(line)) continue; if (line.startswith("#main")) { deck = "main"; } if (deck == "main") { if (!line.startswith("#")) { int cardid = convert.toint32(line.substring(0)); maindeck.items.add(program.carddata[cardid].name); } } if (line.startswith("#extra")) { deck = "extra"; } if (deck == "extra") { if (!line.startswith("#extra") && !line.startswith("!side")) { int cardid = convert.toint32(line.substring(0)); extradeck.items.add(program.carddata[cardid].name); } } if (line.startswith("!side")) { deck = "side"; } if (deck == "side") { if (!line.startswith("!side")) { int cardid = convert.toint32(line.substring(0)); sidedeck.items.add(program.carddata[cardid].name); } } } reader.close(); generatecode(); } }
in other words item "hello"
in list 3 times: want change in list once , "3x hello"
.
use enumerable.distinct
remove duplicates:
maindeck = maindeck.distinct().tolist(); extradeck = extradeck.distinct().tolist(); sidedeck = sidedeck.distinct().tolist();
if want count duplicates first:
int maindeckdups = maindeck.count - maindeck.distinct().count(); int extradeckdups = extradeck.count - extradeck.distinct().count(); int sidedeckdups = sidedeck.count - sidedeck.distinct().count();
if want show how many times item in list use enumerable.groupby
, e.g.:
var maindeckgroups = maindeck.groupby(s => s) .select(g => new { item = g.key, count = g.count() }) .where(x => x.count > 1) .orderbydescending(x => x.count); foreach (var dup in maindeckgroups) console.writeline("{0}x {1}", dup.count, dup.item); // other lists ...
Comments
Post a Comment