Recursive function to split list into list [duplicate] - c#

This question already has answers here:
Split a list into sublist by checking a condition on elements
(3 answers)
Closed 8 years ago.
I'm trying to solve the following problem, I have a Collection that contain some data:
+-------------+---------------+-------------+
| Date | InitialValue | FinalValue |
+-------------+---------------+-------------+
| 21.05.2003 | 0 | 382087.14 |
| 23.06.2003 | 408206.52 | 110622.79 |
| 19.07.2004 | 123811.34 | 0 |
| 31.12.2011 | 0 | 0 |
| 08.06.2012 | 0 | 501854.71 |
| 31.12.2012 | 501854.71 | 546208.19 |
| 31.12.2013 | 634535.58 | 666284.47 |
| 30.06.2014 | 666284.47 | 725837.32 |
| 08.07.2014 | 725837.32 | 729646.48 |
+-------------+---------------+-------------+
What I need to do is to split this list into multiple lists when the final value is equal to 0. The expected result should be something like this:
Result list 1
+-------------+---------------+-------------+
| Date | InitialValue | FinalValue |
+-------------+---------------+-------------+
| 21.05.2003 | 0 | 382087.14 |
| 23.06.2003 | 408206.52 | 110622.79 |
| 19.07.2004 | 123811.34 | 0 |
+-------------+---------------+-------------+
Result list 2
+-------------+---------------+-------------+
| Date | InitialValue | FinalValue |
+-------------+---------------+-------------+
| 31.12.2011 | 0 | 0 |
+-------------+---------------+-------------+
Result list 3
+-------------+---------------+-------------+
| Date | InitialValue | FinalValue |
+-------------+---------------+-------------+
| 08.06.2012 | 0 | 501854.71 |
| 31.12.2012 | 501854.71 | 546208.19 |
| 31.12.2013 | 634535.58 | 666284.47 |
| 30.06.2014 | 666284.47 | 725837.32 |
| 08.07.2014 | 725837.32 | 729646.48 |
+-------------+---------------+-------------+
Can somebody give me an elegant way to solve my problem?

You don't always need linq:
var List<Data> myData;
var List<List<Data>> mySplittedData;
mySplittedData.Add(new List<Data>());
foreach(var item in myData)
{
mySplittedData.Last().Add(item);
if(item.FinalValue == 0)
mySplittedData.Add(new List<Data>());
}
Should work although I'm sure someone will come up with a clever one line linq solution :)

I'm not sure if this is elegant, but it uses Linq all the same:
var result = items.Aggregate(new List<List<Item>> { new List<Item>() }, (list, value) =>
{
list.Last().Add(value);
if (value.FinalValue == 0)
{
list.Add(new List<Item>());
}
return list;
});

Psuedo code
while (more result) {
list = input.Skip(n).TakeWhile(not 0)
n += list.Count()
use or store list
}
Not the most elegant, as the skip will have to skip over the first element of input many times, but might get you started.

Related

How can I add different examples with different columns in specflow examples

The following code is my Scenario:
Scenario: TradeOrders
Given Order 'SellOrder' Has Been Registerd
| Side | Price | Amount | IsFillAndKill | ExpireTime |
| 0 | 100 | 5 | false | 2024-02-05 09:30:26.2080000 |
And Order 'BuyOrder' Has Been Defined
| Side | Price | Amount | IsFillAndKill | ExpireTime |
| <Buy> | <Price> | <Amount> | <IsFillAndKill> | <ExpireTime> |
When I Register The Order 'BuyOrder'
Then The following 'Trade' will be created
| BuyOrderId | SellOrderId | Amount | Price |
| <BuyOrderId> | <SellOrderId> | <TradeAmount> | <TradePrice> |
And BuyOrder 'BuyOrder' Should Be Modified like this
| Side | Price | Amount | IsFillAndKill | ExpireTime |
| 1 | 100 | 0 | false | 2024-02-05 09:30:26.2080000 |
Examples:
| Buy | Price | Amount | IsFillAndKill | ExpireTime |
| 1 | 100 | 5 | false | 2024-02-05 09:30:26.2080000 |
Examples:
| <BuyOrderId> | <SellOrderId> | <TradeAmount> | <TradePrice> |
| 1 | 2 | 5 | 100 |
I want to add some examples with different columns but I have faced with below error:
Severity Code Description Project File Line Suppression State
Error Generation error: Message: The example sets must provide the
same parameters.
I appreciate you in advance.
This is not supported in SpecFlow. Since both tables are used in the same scenario, they need to go in the same row. It makes for a wide table, but there isn't anything you can do about it. Second of all, you cannot have < or > tokens in the column headers.
Examples:
| Buy | Price | Amount | IsFillAndKill | ExpireTime | BuyOrderId | SellOrderId | TradeAmount | TradePrice |
| 1 | 100 | 5 | false | 2024-02-05 09:30:26.2080000 | 1 | 2 | 5 | 100 |
You can also put spaces in the column headers so they are easier to read:
Examples:
| Buy | Price | Amount | Is Fill And Kill | Expire Time | Buy Order Id | Sell Order Id | Trade Amount | Trade Price |
| 1 | 100 | 5 | false | 2024-02-05 09:30:26.2080000 | 1 | 2 | 5 | 100 |
The choice to include spaces in column headers is subjective. It is supported to aid readability, but feel free to omit spaces if this does not make the examples table easier to understand.

How to get all ids in LINQ which two columns dont have predefined values

I need to retrieve all Ids from two columns, which doesnt contain some other list.
For example:
If I have a variable:
I need to select List of rows in All notifications by DeliveryTypeId and NotificationGroupId where those IDs not contained in pair combination in selected notifications.
var selectedNotifications = _dbContext.UserNotificationTypeDeliveryChoice.Include(m => m.NotificationGroup)
.Include(m => m.DeliveryType)
.Where(m => m.UserDefId == userDefId && m.UserTypeId == (int)userType)
.Select(m => new NotificationGroup()
{
NotificationGroupId = m.NotificationGroup.NotificationGroupId,
Name = m.NotificationGroup.Name,
DefaultDeliveryType = new DeliveryType()
{
DeliveryTypeId = m.DeliveryType.DeliveryTypeId,
Name = m.DeliveryType.Name,
HasChoosen = true
}
}).ToList();
var selectedNotificationsMatchingIds = selectedNotifications.Select(n => new { n.NotificationGroupId, n.DefaultDeliveryType.DeliveryTypeId }).ToList();
and I need a condition witch will take all rows from db where is !contains.
example:
//NotificationGroup Codelist
+---------------------+-------------+-----------------------+
| NotificationGroupId | Name | DefaultDeliveryTypeId |
+=====================+=============+=======================+
| 1 | Comments | 1 |
+---------------------+-------------+-----------------------+
| 2 | QA | 1 |
+---------------------+-------------+-----------------------+
| 3 | Services | 1 |
+---------------------+-------------+-----------------------+
| 4 | eScheduling | 1 |
+---------------------+-------------+-----------------------+
| 5 | eDelivery | 2 |
+---------------------+-------------+-----------------------+
//Delivery Type Codelist
+----------------+-----------------+
| DeliveryTypeId | Name |
+================+=================+
| 1 | SMS |
+----------------+-----------------+
| 2 | Email |
+----------------+-----------------+
| 3 | PortalMessaging |
+----------------+-----------------+
//SELECTED NOTIFICATIONS
+--------------------------------------+-----------+----------------------------+---------------------+----------------+------------+
| UserNotificationTypeDeliveryChoiceId | UserDefID | UserCompanyOrInstitutionId | NotificationGroupId | DeliveryTypeId | UserTypeId |
+======================================+===========+============================+=====================+================+============+
| 269 | 2933 | NULL | 1 | 2 | 1 |
+--------------------------------------+-----------+----------------------------+---------------------+----------------+------------+
| 270 | 2933 | NULL | 2 | 2 | 1 |
+--------------------------------------+-----------+----------------------------+---------------------+----------------+------------+
| 271 | 2933 | NULL | 3 | 2 | 1 |
+--------------------------------------+-----------+----------------------------+---------------------+----------------+------------+
| 272 | 2933 | NULL | 4 | 2 | 1 |
+--------------------------------------+-----------+----------------------------+---------------------+----------------+------------+
| 273 | 2933 | NULL | 4 | 1 | 1 |
+--------------------------------------+-----------+----------------------------+---------------------+----------------+------------+
//ALL NOTIIFICATIONS
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| NotificationGroupUserTypeId | NotificationGroupChangeTypeId | UserTypeId | NotificationGroupId | NotificationTemplateId | DateCreated | DeliveryTypeId |
+=============================+===============================+============+=====================+========================+=========================+================+
| 1 | NULL | 1 | 1 | 14 | NULL | 1 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 6 | 11 | 1 | 4 | 21 | 2011-07-18 11:13:23.543 | 2 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 17 | NULL | 1 | 4 | 6 | NULL | 2 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 26 | NULL | 1 | 3 | 8 | NULL | 2 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 30 | 11 | 1 | 4 | 15 | 2011-07-17 13:16:36.897 | 1 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 31 | 14 | 1 | 4 | 16 | 2011-07-17 13:17:00.880 | 1 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 32 | 15 | 1 | 4 | 17 | 2011-07-17 13:17:18.220 | 1 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 33 | 16 | 1 | 4 | 18 | 2011-07-17 13:17:34.833 | 1 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 34 | 17 | 1 | 4 | 19 | 2011-07-17 13:17:58.337 | 1 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 35 | 18 | 1 | 4 | 20 | 2011-07-17 13:18:35.960 | 1 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 36 | 14 | 1 | 4 | 22 | 2011-07-18 16:00:27.320 | 2 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 37 | 15 | 1 | 4 | 23 | 2011-07-18 16:01:17.843 | 2 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 38 | 16 | 1 | 4 | 24 | 2011-07-18 16:01:36.300 | 2 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 39 | 17 | 1 | 4 | 25 | 2011-07-18 16:01:55.923 | 2 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 40 | 18 | 1 | 4 | 26 | 2011-07-18 16:02:12.607 | 2 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 41 | 8 | 1 | 3 | 27 | 2011-11-09 12:59:51.307 | 2 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 44 | 19 | 1 | 3 | 28 | 2011-12-21 14:57:31.780 | 2 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 48 | 20 | 1 | 5 | 29 | 2011-12-23 10:19:16.840 | 2 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
| 49 | 1 | 1 | 3 | 6 | 2011-12-22 16:09:15.047 | 2 |
+-----------------------------+-------------------------------+------------+---------------------+------------------------+-------------------------+----------------+
So I am getting in selectedNotifications correct pairs, but then when I try to filter my new query, I m getting only two pairs but I should get it (with these example):
var notSelectedNotifications = _dbContext.NotificationGroupUserType.Include(m => m.DeliveryType)
.Include(m => m.NotificationGroup)
.Where(m => m.UserTypeId == (int)userType)
.Where(m => !selectedNotificationsMatchingIds.Contains(new { m.NotificationGroup.NotificationGroupId, m.DeliveryType.DeliveryTypeId }))
.Select(m => new NotificationGroup()
{
NotificationGroupId = m.NotificationGroupId,
Name = m.NotificationGroup.Name,
DefaultDeliveryType = new DeliveryType()
{
DeliveryTypeId = m.DeliveryType.DeliveryTypeId,
Name = m.DeliveryType.Name,
HasChoosen = false
}
}).ToList();
Any advise is welcomed. If someone can tell me, how to get all of these which is not selected in selectedNotificationsMatchingIds
The Contains() method usage default equality comparer when implementation of IEqualityComparer<T> is not provided for element stored in collection. Obviously the default equality comparer will not work for element of Anonymous class stored in selectedNotificationsMatchingIds.
You have two options:
Option 1: Re-write Where condition to use Any as:
//.Where(m => !selectedNotificationsMatchingIds
// .Contains(new { m.NotificationGroup.NotificationGroupId,
// m.DeliveryType.DeliveryTypeId }))
.Where(m => !selectedNotificationsMatchingIds
.Any(c => c.NotificationGroup.NotificationGroupId == m.NotificationGroupId
&& c.DeliveryTypeId == m.DeliveryType.DeliveryTypeId))
Option 2: Create a class having properties for NotificationGroupId and DeliveryTypeId and implement IEqualityComparer<T> interface for it. Then only you can use object of that class as part of .Contains() method.

Convert T-sql to Linq or Entityframework and not to use SqlQuery() for raw queries

I have a table which is called Signer :
+--------------+----------+---------+--------+--------------+---------+-----------+
| Name | User | Order | Signed | CompanyName | Status | InvoiceId |
+--------------+----------+---------+--------+--------------+---------+-----------+
| Anders | aa | 1 | 0 | OvnAnd2 | 0 | 26650 |
| Peyman | pm | 2 | 1 | OvnAnd2 | 1 | 26650 |
| Siw Ericsson | se | 3 | 0 | OvnAnd2 | 0 | 26650 |
| test | test | 4 | 0 | OvnAnd2 | 0 | 26650 |
|Siw Ericsson | se | 1 | 0 | OvnAnd2 | 0 | 26652 |
| test | test | 2 | 1 | OvnAnd2 | 0 | 26652 |
|Siw Ericsson | se | 1 | 0 | OvnAnd2 | 0 | 25365 |
+--------------+----------+---------+--------+--------------+---------+-----------+
Goal:
As you can see I have 3 different InvoiceId's. For each InvoiceId, I would like to find a row with minimum order number that Status column's value is 0 and User column has to be se.
( It means, Show the current users related invoices which are ready to be signed based on his/her username, order, signed columns)
I came up with this T-SQL which works fine :
select * from Signer s1
where s1.User = 'se' and Order = (select min(Order) from Signer s2 where s2.InvoiceId = s1.InvoiceId and Signed = 0)
And the result:
+--------------+----------+---------+--------+--------------+---------+-----------+
| Name | User | Order | Signed | CompanyName | Status | InvoiceId |
+--------------+----------+---------+--------+--------------+---------+-----------+
|Siw Ericsson | se | 1 | 0 | OvnAnd2 | 0 | 26652 |
|Siw Ericsson | se | 1 | 0 | OvnAnd2 | 0 | 25365 |
+--------------+----------+---------+--------+--------------+---------+-----------+
I would like to convert this query from T-Sql to Linq or EntityFramework :
This is my solution:
var temp = from x in db.Signers
where x.User == Me.UserName &&
x.Signed == 0
group x by x.InvoiceId
into item
select new
{
item.Key,
item = item.Min(x => x.Order)
};
Which returns 3 rows which is wrong because Siw should see the related invoices that are ready to be signed by her. (It means the first row should not be in the list)
+--------------+----------+---------+--------+--------------+---------+-----------+
| Name | User | Order | Signed | CompanyName | Status | InvoiceId |
+--------------+----------+---------+--------+--------------+---------+-----------+
| Anders | aa | 1 | 0 | OvnAnd2 | 0 | 26650 |
|Siw Ericsson | se | 1 | 0 | OvnAnd2 | 0 | 26652 |
|Siw Ericsson | se | 1 | 0 | OvnAnd2 | 0 | 25365 |
+--------------+----------+---------+--------+--------------+---------+-----------+
More info:
- As you can see in the first table, we have a special logic that someone can sign invoices out of order and Peyman is one of them.
- I don't want to use SqlQuery() method in Entityframework in order to execute t-sql queries.
I appreciate any help to find a solution for my goal.
Best regards
I think this is one of those situations where "let" come in handy:
var result = from s in Signers
let minToSign = Signers.Where(si =>
si.InvoiceId == s.InvoiceId && si.Signed == 0
).Min(si => si.Order)
where s.User == "se" && s.Order == minToSign
select s;

Approach to read a text file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a predefined List<string> Wellnames = new List<string>(){"CAM1","CAM2","CAM3"};
I have a text file, which is always in the same format as shown. How do I extract/read the highlighted numbers in the example? i,e. for CAM1 and similarly for CAM2 and CAM3.
here is the excerpt of the file:
1------------------------------------------------------------------------------------------------------------------------------913
ALLOC Allocation/bundle report 10835.0000 Days report step 228, 1 Sep 2015
------------------------------------------------------------------------------------------------------------------------------
|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Streamline | | | | | | |
| Bundle | | Surface Rate | Surface Volumes | | | |
|------------------------| Flow |-----------------------------------------------------------------------------------------------------------| Total Reservoir | Pore |PV weighted|
| Start | End | Direct | Oil | Water | Gas | Oil | Water | Gas | Rate | Volume | Pressure |
|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| | SM3/D | Fraction | SM3/D | Fraction | SM3/D | Fraction | SM3 | SM3 | SM3 | RM3/D | Fraction | RM3 | Bar |
| |-----------------------------------------------------------------------------------------------------------------------------------------------------------|
| CAM1 | | 9.13e-001 | | 3.14e+001 | | 9.13e-001 | | 7.55e+004 | 1.50e+005 | 7.55e+004 | 3.26e+001 | 1.06e+000 | 2.29e+005 | 6.21e+001 |
| CAM1 CAM138 | Outflow | 2.82e-001 | 3.09e-001 | 9.63e+000 | 3.07e-001 | 2.82e-001 | 3.09e-001 | 1.99e+004 | 3.88e+004 | 1.99e+004 | 1.00e+001 | 3.07e-001 | 5.96e+004 | 6.17e+001 |
| CAM1 CAM255 | Outflow | 3.34e-002 | 3.66e-002 | 3.00e+000 | 9.57e-002 | 3.34e-002 | 3.66e-002 | 1.86e+004 | 4.05e+004 | 1.86e+004 | 3.07e+000 | 9.40e-002 | 6.00e+004 | 6.30e+001 |
| CAM1 CAM177 | Outflow | 2.12e-001 | 2.32e-001 | 1.10e+001 | 3.50e-001 | 2.12e-001 | 2.32e-001 | 1.94e+004 | 3.66e+004 | 1.94e+004 | 1.13e+001 | 3.46e-001 | 5.68e+004 | 6.13e+001 |
| CAM1 CAM582 | Outflow | 3.17e-001 | 3.47e-001 | 5.72e+000 | 1.82e-001 | 3.17e-001 | 3.47e-001 | 7.77e+003 | 1.33e+004 | 7.77e+003 | 6.10e+000 | 1.87e-001 | 2.14e+004 | 6.13e+001 |
| CAM1 CAM354 | Outflow | 6.87e-002 | 7.53e-002 | 2.05e+000 | 6.53e-002 | 6.87e-002 | 7.53e-002 | 9.80e+003 | 2.04e+004 | 9.80e+003 | 2.14e+000 | 6.56e-002 | 3.07e+004 | 6.34e+001 |
|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
this Regex will get you what you need.
#"\|\s+CAM1\s+(\S+)\s+\|\s+\S+\s+\|\s+(\S+)\s+\|\s+\S+\s+\|\s+(\S+)\s+\|\s+\S+\s+\|\s+(\S+)"
just change CAM1 for what you are looking for.
I put together an example for you here
I'm assuming you know how to read the file line-by-line. Once you have a particular data line in a string, you can use the Split() method on the '|' character. You'll get back a zero-based array, with each element holding the data from one column. Index into the array at index 0 and trim the value to check for your identifier CAM1, etc. If it's the one you want, you can grab the other values from their indexes in the array.
Seems like the simplest approach given the rigid data format.
IMO the best approach for solving this, is to iterate the file line by line using a StreamReader and then parsing out the necessary information.
public dynamic Read(string file)
{
using (var streamReader = new StreamReader(File.OpenRead(file))
{
while ((var line = streamReader.ReadLine()) != null)
{
if (line.StartsWith("| CAM", StringComparison.OrdinalIgnoreCase))
{
var columns = line.Split('|').Select(x => x.Trim());
// Parse the values here, put them in a DTO
}
}
}
}

merge 2 different datatable using DataRelation

I tried to merge 2 datatables like this. But my tables have different schema and different amount of rows. So I get an error here:
DataRelation drel = new DataRelation("EquiJoin",cr1, cr2, true);
dataSet.Relations.Add(drel);//error
As far as I understand, because first table has much more rows than second table.
Error: Cannot evaluate expression because a native frame is on top of the call stack.
Tables look like:
snowFlake: snow:
f_text | f_link_id | f_tabkey | | f_text | f_link_id | f_tabkey |
--------+---------------+-------------| |---------+---------------+-------------|
row1 | 100001 | 1 | | - | 100000 | 1 |
row2 | 100001 | 2 | | + | 100001 | 1 |
row3 | 100001 | 3 | | - | 100001 | 2 |
row4 | 100002 | 1 | | + | 100001 | 3 |
row5 | 100003 | 1 | | + | 100002 | 1 |
| + | 100003 | 1 |
| - | 100003 | 1 |
| + | 100004 | 1 |
| - | 100005 | 1 |
Primary keys that I use:
snowFlake.PrimaryKey = new DataColumn [] { snowFlake.Columns[IndexesField.F_LINK_ID], snowFlake.Columns[IndexesField.F_TABKEY] };
snow.PrimaryKey = new DataColumn [] { snow.Columns[IndexesField.F_LINK_ID], snow.Columns[IndexesField.F_TABKEY] };
DataColumn[] cr1 = { snowFlake.Columns[IndexesField.F_LINK_ID], snowFlake.Columns[IndexesField.F_TABKEY] };
DataColumn[] cr2 = { snow.Columns[IndexesField.F_LINK_ID], snow.Columns[IndexesField.F_TABKEY] };
How can I solve it?
Regards, Alexander.
Doesn't matter if they do not have same number of rows, because they are joined over a relation thus mimicking TSQL's Inner Join behavior. Without telling us the specific error, one can only assume that you haven't properly defined keys for joining (for example, the columns you specified in the relation don't exist).

Categories

Resources