Please Help me in the following...
I have two list objects as follows:
list1:
ID col1
--------
1 A
1 B
1 C
list2:
ID col2
--------
1 D
1 E
1 F
Now I want:
ID col1 col2
---------------
1 A D
1 B E
1 C F
So basically column1 then column 2 from list1 then column 3 from list 2. Column1 is common.
Please note that the number of rows may not be always same.. in that case it will be null.
I really really need this solution in Linq. Thanks.
List<Class> list1 = new List<Class>();
List<Class> list2 = new List<Class>();
// Add classes to lists...
list1.AddRange(list2);
// Order merged list...
list1.OrderByDescending(o => o.col1).ThenBy(o => o.col2);
Trying to understand...
Dictionary<Int32, Class[]> dictionary = new Dictionary<Int32, Class[]>();
list2.Reverse();
for (Int32 i = 0; i < list1.Count; ++i)
dictionary[i] = new Class[2] { list1[i], list2[i] };
I really donĀ“t understand why was hard for get clear the question, he only want have two array combined in one (still i don't know why in the aswers of the web you only find Concat,AddRange or Union. Wrong Answers For this Question):
I solve it with Zip:
var result = list1.Zip(list2,(first,second)=>new {entrada=first,salida=second});
Now You Can do Something like this:
var union=result.Select(x=> new {x.entrada, x.salida, horas = int.Parse((DateTime.Parse(x.salida).Subtract(DateTime.Parse(x.entrada))).Hours.ToString()) });
Related
I have list of ids like this below
List<int> ids = new List<int>();
and then i have list of lengths which is also integers like this below..
List<int> lengths = new List<int>();
now i need to insert into table using linq query with the data format like this below
ID length
1 1
1 2
1 3
2 1
2 2
2 3
for that i am doing like this
foreach (var item in ids)
{
foreach (var item in lengths)
{
}
}
With the above way i am not able insert the multiple id's in the table .. I am hoping there should be better way to do this..
Could any one please suggest any ideas on this one that would be very grateful to me..
Thanks in advance.
If you wanted to project these 2 lists to a flattened list with LINQ, you could use SelectMany
Projects each element of a sequence to an IEnumerable and flattens
the resulting sequences into one sequence.
// projecting to an anonymous type
var results = ids.SelectMany(id => lengths.Select(length => new {id, length }));
// or projecting to a value tuple
var results = ids.SelectMany(id => lengths.Select(length => (id, length)));
If you really want a single loop, you can loop over the final result length and compute the indexes into each List:
var idsCount = ids.Count;
var lengthsCount = lengths.Count;
var totalCount = idsCount * lengthsCount;
for (int j1 = 0; j1 < totalCount; ++j1) {
var id = ids[j1 / lengthsCount];
var length = lengths[j1 % lengthsCount];
new { id, length }.Dump();
// insert id,length
}
I have two lists in C#.
public List<MyClass> objectList = new List<MyClass>(); // it is filled with MyClass objects
public List<int> numberList = new List<int>(); // it is filled with numbers
The index of numbers in the numberList correspond to object index in the objectList: For example: objectList[0] = o1 and numberList[0] = 3 ;
objectList[1] = o2 and numberList[1] = 5 ...
objectList: |o1 | o2 | o3 | o4 | o5 | ...
numberList: 3 5 6 1 4 ...
I want to sort the numbers in the numberList in ascending order and I want for the objetcs in objectList to move with them:
After sorting:
objectList: |o4 | o1 | o5 | o2 | o3 | ...
numberList: 1 3 4 5 6 ...
In practical use I need this for implementing the Hill climbing algorithm on a N queen problem. In the objectList I store positions of all the queens on the board and in the numberList I store the calculated heuristics for the positions. Then I want to sort the numberList so I get the position with the lowest heuristic value. The goal is to move to the position with the lowest heuristic value.
Transform your object list into a sequence of items paired with their indices:
var pairs = objectList.Select(item, index) => new { item, index };
Now you have something you can use to do an ordering:
var orderedPairs = pairs.OrderBy(pair => numberList[pair.index]);
Now you have an ordered list of pairs. Turn that back into an ordered list of items:
var ordered = orderedPairs.Select(pair => pair.item);
and turn it into a list:
var orderedList = ordered.ToList();
Note that your original lists are not altered. This creates a new list that is in the order you want.
Of course you can do it all in one expression if you like:
objectList = objectList
.Select((item, index) => new { item, index } )
.OrderBy(pair => numberList[pair.index])
.Select(pair => pair.item)
.ToList();
Now, all that said: it sounds like you're doing too much work here because you've chosen the wrong data structure. It sounds to me like your problem needs a min heap implementation of a priority queue, not a pair of lists. Is there some reason why you're not using a priority queue?
Let's say I have this list:
1
1
1
1
2
2
2
3
I want to narrow it down with C# to a list with a maximum of two same items in a list so it would look like this:
1
1
2
2
3
I used to use 'distinct' like this:
string[] array = System.IO.File.ReadAllLines(#"C:\list.txt");
List<string> list = new List<string>(array);
List<string> distinct = list.Distinct().ToList();
but don't have an idea on how it could bring a max number of same values
You could do it with Linq as follows.
var Groups = Input.GroupBy( i => i );
var Result = Groups.SelectMany( iGroup => iGroup.Take(2) ).ToArray();
I have a question about sorting in Datatable. I have a table like below and want to sort it from small to big. The problem is when i have same numbers, i want to have the first as the last and so on...
Table:-----------------------------------After Sorting:
Name Bit Size Name Bit Size (corrected)
A 0 1 A 0 1
C 1 2 C 1 2
B 1 3 B 1 3
D 1 1 D 1 1
Result that i want:
Name Bit Size (corrected)
A 0 1
D 1 1
B 1 3
C 1 2
My Code:
arraySBit.DefaultView.Sort = "Bit";
arraySBit = arraySBit.DefaultView.ToTable();
You can use Linq-To-DataTable:
var tblSorted = table.AsEnumerable()
.OrderBy(r => r.Field<int>("Bit"))
.CopyToDataTable();
Edit: But actually DataView.Sort should also work (tested).
Since you have edited your question. Your requirement seems weired. If the Bit is the same you don't want to order by something but you want to reverse the "order" of the rows of the equal rows (so the Ordinal position in the DataTable).
This does what you want although i'm not sure that it's really what you need:
DataTable tblSorted = table.AsEnumerable()
.Select((Row, Ordinal) => new {Row,Ordinal})
.OrderBy(x => x.Row.Field<int>("Bit"))
.ThenByDescending(x => x.Ordinal)
.Select(x => x.Row)
.CopyToDataTable();
Basically it passes the index of the row in the table via this overload Enumerable.Select into an anonymous type. Then it'll sort by Bit first and the index/ordinal second.
A workaround,
After these lines, you should have result in arrySBit as you want
DataTable arrySBitClone = arrySBit.Copy();
arrySBit.DefaultViewSort.Sort = "Bit";
bool different = false;
for(int i=0; i<arrySBit.Rows.Count; i++)
{
if(arrySBit.Rows[i]["Bit"]!=arrySBitClone.Rows[i]["Bit"])
{
difference = true;
break;
}
}
if(!different)
{
arrySBit = arrySBit.Copy();
}
if i'm getting right your question.
why not use Select?
DataTable dt = arraySBit.Select("", "Bit, Size").CopyToDataTable();
The first parameter of the Select Method is a condition to filter, the second is an Order By, so it should work
I have the following query:
var results = from theData in GeometricAverage
group theData by new { study = theData.study, groupNumber = theData.groupNumber, GeoAverage= theData.GeoAverage } into grp
select new
{
study = grp.Key.study,
groupNumber = grp.Key.groupNumber,
TGI = testFunction(grp.Key.GeoAverage, Also here I want to pass in the GeoAverage for only group 1 (but for each individual study))
};
What I want to do is that for each study, there are multiple groups with a GeoAverage figure for each group. The TGI is calculated by passing the GeoAverage figure for each group and the GeoAverage figure for group 1 (on each study) into the testFunction. I can't figure out how to pass in the value just for group 1.
Hope this makes sense.
EDIT: Sample of data:
Study Group GeoAverage
1 1 3
1 2 5
1 3 6
2 1 2
2 2 3
2 3 9
So, for the above data, I would want each GeoAverage figure for each group, to be evaluated against the GeoAverage figure of group 1 within that same study. So if I have say a function:
int foo(int a, int b)
{
return a * b;
}
Using the data above, I would first evaluate study 1, group 1 against itself, so pass in GeoAverage 3 twice and return 9. For Study 1, group 2, pass in group 2 GA at 5, and that studys group1 GA at 3, returning 15.
Have now worked it out. I iterate through a collection of data that I want the value to be stored against and use the following two LINQ queries:
foreach (var data in compoundData)
{
var controlValue = from d in GeometricAverage
where d.study == data.study
where d.groupNumber == "1"
select d.GeoAverage;
var treatmentValue = from l in GeometricAverage
where l.study == data.study
where l.groupNumber == data.groupNumber
select l.GeoAverage;
data.TGI = CalculateTGI(controlValue, treatmentValue);
}