ImtehQ ImtehQ - 6 months ago 45
C# Question

c# Loop trough class list but only once for multiple names

I think it can be done with linq but i cant find it on google, as i really done have a idea how to look for this issue.

I have a class list like this:

Public class Data
public string name;
public int someData;
public List<Data> allData = new List<Data>();

The list may contain like 32 items, where somedata is generated but the name is taken of the object that someData belongs to.
But there might be multiple enterys by the same name, this is easyer to work with later on then 1 name with a int array.

What im looking for is a way to go tough the intire allData list but only once for each name, so 'bob' might be in there 8 times but i want to look trough it and only visit bob once.

It there a way to do this or do i need to rethink my list, and do use a int array?

And feedback is great!

Answer Source

Why not use a dictionary with key for the name and integer array or list:

var allData = new Dictionary<string, List<int>>();
allData["Bob"] = new List<int>() { 1 , 2 , 3 };
var allInts = allData.Values.SelectMany(m => m); // IEnumerable<int>
var intsByName = allData["nameToSelect"]; // List<int>
var availableNames = allData.Keys;

There is no harm in your proposed data structure either:

var allInts = allData
    .Select(m => m.someData); // IEnumerable<int>
var intsByName = allData
    .Where(m =>"nameToSelect"))
    .Select(m => m.someData); // IEnumerable<int>
var availableNames = allData.Select(m =>;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download