How get array element from list some object - c#

public class Ex
{
public string example1{get;set;}
public string example2{get;set;}
public Test test{get;set;}
}
public class Test
{
public string example3 {get;set;}
public long[] arrayLong{get;set;}
}
I have List listEx for example 10 elements. How get arraylong?
long[] result = listEx.Select( x=> x.Test.Select(y =>y.arrayLong)).ToArray();
I need only long[] how parse it?

Use SelectMany function, which will "flatten" collection of collections to one collection.
var result = listEx.SelectMany(ex => ex.Test.Select(test => test.arrayLong)).ToArray();
From MSDN: Enumerable.SelectMany Method

You should use SelectMany
var outresult = listEx.SelectMany(t => t.Test.Select(s => s.arrayLong)).ToArray();

Related

Linq: Select KeyValuePair from dictionary where value is a list of objects

I have a field that looks like:
public Dictionary<ClassA, List<ClassB>> MyDict;
Assume that:
public class ClassA
{
public string Name;
public int Id;
}
public class ClassB
{
public string Tag;
public string Text;
}
I'm trying to define a query that is of IEnumerable<KeyValuePair<ClassA,IEnumerable<ClassB>> type where I define a condition on the value of ClassB.Tag. I tried things like:
IEnumerable<KeyValuePair<ClassA,IEnumerable<ClassB>> q =
MyDict.Where(pair => pair.Value.Any(b => b.Tag == "a tag"));
But obviously the above is not what I need because it returns the whole List<ClassB> if any item matches that condition, while what I want is to return an IEnumrable or a List of items that match the condition.
dotNetFiddle demo
You need to construct the IEnumerable from a call to ToDictionary, where you use a projection to only take the matching BClass from the list and only take the result from that set where values in the BClass list were actually matched.
IEnumerable<KeyValuePair<ClassA,List<ClassB>>> q = MyDict.ToDictionary(
k => k.Key,
k => k.Value.Where(b => b.Tag == "10").ToList()
).Where(kv => kv.Value.Any());

C# Linq to group by object properties

I have the following classes:
public class MyItem
{
public string Email;
public int Value1;
public datetime Value2;
//etc
}
public class MyItems : List<MyItem> {}
I populate a MyItems object with a list of random items. Now I need to break this list into smaller lists, whereby each list contains only the items that have the same 'Email' property.
Can this be achieved using Linq?
If you have a List<MyItem> you can simply use GroupBy:
myItems.GroupBy(x => x.Email).Select(g => g.ToList());
This will return a IEnumerable<List<MyItem>>
Or you can use ToDictionary and you can access your groups by Email:
myItems.GroupBy(x => x.Email).ToDictionary(x => x.Key, x => x.ToList());
Try this
MyItems myItems = new MyItems();
//Populate here
myItems.GroupBy(x => x.Email).Select(group => group.ToList());
Here you get a collection of lists that you can use

sorting list in a list

I have two classes
public class X
{
string title;
}
public class Y
{
string name;
IList<X> testList;
}
I have a list like below
IList<Y> myList = new List<Y>();
I want to sort myList based on the name and title
How can I do it?
Try something like this,
var sorted = lstY.OrderBy(c => c.name).ToList().Select(d => { d.testList.OrderBy(f => f.title); return d; });
myList.OrderBy(x => x.name).ThenBy(y => y.testList.Min(z=>z.title));
This is one option but not the only option. Add a public or internal getter to class Y:
public IEnumerable<X> TestList{get{return testList.OrderBy(x=>x.title);}}
When retrieving your list of Y, clearly you can sort it by name:
myList.OrderBy(y=>y.name);
And for whatever processing you are doing, such as diplaying the list of Y, you would display Y.name and foreach X in TestList the X.title will be sorted.
or even without that second getter:
myList.OrderBy(y=>y.name).Select(y=>new{y.name, testList=y.testList.OrderBy(t=>t.title)}).Dump();

Find Index from List

I have a Dictionary that contains thread Information Dictionary<String,Thread>
"2FF"
"2IE"
"7CH"
etc
what i know is integers 2,7 etc what i want to know that in Dictionary how many strings contain the given integer if it is there then get that string
Eg
String GetString(int integer)
{
//if Dictionary contains given intgr return whole string in which that integer is present
}
}
With LINQ syntax:
var matchingThreads = from pair in dictionary
where pair.Key.StartsWith(number.ToString())
select pair.Value;
With traditional syntax:
var matchingThreads = dictionary
.Where(pair => pair.Key.StartsWith(number.ToString()))
.Select(pair => pair.Value);
If you only need to count them and you don't care about the Thread objects, you can use:
int count = dictionary.Keys.Count(key => key.StartsWith(number.ToString()))
Note that you need a using System.Linq directive.
Maybe a List<CustomClass> would be a better choice here where CustomClass would look like:
public sealed class CustomClass
{
public Thread Thread { get; set; }
public string String { get; set; }
}
(Better property names are alway good, of course :-) )
A dictionary is not sutitable if you do not know the exact keys or only parts of them.
You could then use LINQ to find out what you want, e.g.:
int count = list.Where(c => c.String.StartsWith(integer.ToString())).Count();
//or
IEnumerable<string> strings = list.Where(c => c.String.StartsWith(integer.ToString())).Select(c => c.String);
public IEnumerable<string> GetMatchingKeys(int value)
{
var valueText = value.ToString();
return _dictionary.Keys.Where(key => key.Contains(valueText));
}

LINQ - Select correct values from nested collection

Consider the following class hierarchy:
public class Foo
{
public string Name { get; set; }
public int Value { get; set; }
}
public class Bar
{
public string Name { get; set; }
public IEnumerable<Foo> TheFoo { get; set; }
}
public class Host
{
public void Go()
{
IEnumerable<Bar> allBar = //Build up some large list
//Get Dictionary<Bar, Foo> with max foo value
}
}
What I would like to do using Linq2Objects is to get an KeyValuePair where for each Bar in the allBBar collection we select the Foo with the maximum Value property. Can this be done easily in a single LINQ statement?
Sure, although my preferred solution uses MaxBy from MoreLINQ:
var query = allBar.ToDictionary(x => x, // Key
x => x.TheFoo.MaxBy(f => f.Value));
Note that this will go pear-shaped if TheFoo is empty for any Bar instance.
Another way using Aggregate instead of OrderBy so that figuring out the max Foo is O(n) instead of O(n log n):
var query = allBar.ToDictionary(
bar => bar,
bar => bar.TheFoo.Aggregate(
null,
(max, foo) => (max == null || foo.Value > max.Value) ? foo : max));
just to add to Jon's comment about MaxBy going pear shaped if you have no foos, you could do an OrderByDescending and then use FirstOrDefault to get at the Max element. If the collection is empty it'd just return null instead of going "pear shaped".
var foobars = bars.ToDictionary(bar => bar,
bar => bar.TheFoo.OrderByDescending(foo => foo.Value).FirstOrDefault());
I don't think this wouldn't be as efficient as MaxBy, but it'd be more robust in the case of an empty collection.

Categories

Resources