1

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!

2
  • stackoverflow.com/questions/10255121/… Commented Aug 28, 2017 at 2:11
  • "go trough the entire 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." - this doesn't make sense. If "bob" is in the list 8 times and you got through the list you must visit "bob" 8 times. Commented Aug 28, 2017 at 2:21

1 Answer 1

1

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 => m.name.Equals("nameToSelect"))
    .Select(m => m.someData); // IEnumerable<int>
var availableNames = allData.Select(m => m.name).Distinct();
Sign up to request clarification or add additional context in comments.

7 Comments

I dont know if its "bob", the name is basicly random
Just thinking if you need to find all the integers with the string key, a dictionary would make it easier to organize, access, and expand the list.
well to give a bit more info, i know know how full the list will be nor do i know what items will go in there, so i dont know the names nor the int data in it, Later on i need to access the all the combined int data, and sometimes i need to get only the int data that matches a name
I put in examples for each of the scenarios you suggested. SelectMany in LINQ will get you all the int data combined. Then you can just directly access the matching name by using the dictionary structure.
Yes that will work but i dont know nameToSelect, i dont know what names are in there
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.